Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Fault in url path?
Tank you for all the help! Still studying Django and trying to figure it out. In my program, I have a fault and I've tried different ways to go around it, but it persists... And I cannot find any similar case to combat it... If possible, if you see where is my mistake, could you please also explain my conceptual mistake? It feels that I don't understand something important about Django... I understand python, SQL, but it feels like each time I am fighting with Django:(... Like I am rubbing a cat the wrong way. I am trying to build the form, which connects to the PostgreSQL database and saves information in it. The code as follows: models.py: from django.db import models from django import forms from django.urls import reverse from django.forms import ModelForm class ForQuery(models.Model): query_id = models.BigAutoField(primary_key=True)//I would like to have my own automatic int field worker_name = models.CharField(max_length=35, blank=True, null=True) dep_name = models.ForeignKey(Classification, models.DO_NOTHING, db_column='dep_name', blank=True, null=True) forms.py: class ForQueryForm(forms.ModelForm): class Meta: model=ForQuery fields=('work_name', 'dep_name')//only one field has to be entered while form. the other chosen. urls.py: urlpatterns = [ //both paths are extensions from generic page. Which is the main page for the program path('', views.index, … -
django ImportError: cannot import name 'connections'
I get this error: from django.conf import connections ImportError: cannot import name 'connections' In my code: from django.conf import connections def fetch_filter_rule_sql_from_ui_db(filter_rule_id): with connections['frontend'].cursor() as cursor: query = "SELECT id, name FROM dmf_filter_rules" cursor.execute(query) return dictfetchall(cursor) -
Django migration script "out of range"
I got following migration in django: import re from django.db import migrations def insert_numeric_software_version(apps, scheme_editor): Device = apps.get_model("devices", "Device") for device in Device.objects.all(): if device.software_version is not None: device.numeric_software_version = numeric_version(device.software_version) def numeric_version(version): digits = 4 pattern = r"(\d+).(\d+).(\d+)" major, minor, patch = tuple(map(int, re.findall(pattern, version)[0])) return patch + pow(10, digits) * minor + pow(10, 2 * digits) * major class Migration(migrations.Migration): dependencies = [ ("devices", "0035_merge_20200410_1529"), ] operations = [migrations.RunPython(insert_numeric_software_version)] It should fill the "numeric_software_version" field in the database with numeric fields. In the model this field is: numeric_software_version = models.IntegerField(default=0) When I run "python manage.py migrate" I got following error: File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.6/site-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.6/site-packages/django/core/management/base.py", line 364, in execute output = self.handle(*args, **options) File "/usr/local/lib/python3.6/site-packages/django/core/management/base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "/usr/local/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 234, in handle fake_initial=fake_initial, File "/usr/local/lib/python3.6/site-packages/django/db/migrations/executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "/usr/local/lib/python3.6/site-packages/django/db/migrations/executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/usr/local/lib/python3.6/site-packages/django/db/migrations/executor.py", line 245, in apply_migration state = migration.apply(state, schema_editor) File "/usr/local/lib/python3.6/site-packages/django/db/migrations/migration.py", line 124, in apply operation.database_forwards(self.app_label, … -
List categories in footer in every view
I want to have my categories in the footer on any template I include my footer in. I have a Category model and currently how I'm doing this is to import all category objects through my context. Obviously this is pretty redundant. views.py def homepage_view(request): context = { "categories": Category.objects.all(), } return render(request=request, template_name='main/index.html', context=context) -
How to join multiple models using Django without involving foreign keys?
Views.py class IzlazniRacuni(viewsets.ModelViewSet): def get(self, req): r = Racuniizlaznifinancijski.objects.all() p = Poslovnipartneri.objects.all() data = { "Racuniizlaznifinancijski": RacuniizlaznifinancijskiSerializers(r, many=True).data, "Poslovnipartneri": PoslovnipartneriSerializers(p, many=True).data, } return JsonResponse(data) Urls.py router.register('IzlazniRacuni', views.IzlazniRacuni, basename='IzlazniRacuni') I refresh my command prompt and it is written that everything is fine. I go to http://127.0.0.1:8000/api/IzlazniRacuni/ and got Server Error 500 as a message. -
Update model value django (boolean field) through button HTML
How can i change model value from my models.py using html button, so this is my models.py and main.html [models.py][1] class Note(models.Model): topic = models.ForeignKey(Topic, null=True, on_delete=models.SET_NULL) notes = models.TextField(max_length=3000, null=True) title = models.CharField(max_length=200, null=True) clear = models.BooleanField(default=False) date_created = models.DateTimeField(auto_now_add=True, null=True) [main.html][2] <div class="col"> {% if note.clear %} <button class="btn btn-primary btn-sm btn-note">Unclear</button> {% else %} <button class="btn btn-primary btn-sm btn-note">Clear</button> {% endif %} </div> i want to change that "clear" value to true or false everytime i click the button "btn-note" thanks -
POST request gets 502 error with gunicorn+nginx, works well with runserver+nginx
I have the following code for my user registration view -- it works with runserver but not with gunicorn: class SignupView(AllauthSignupView): """Overrides the SignUpView of Allauth to keep the email field if present in the URL QueryDict.""" def get_initial(self): initial = super(SignupView, self).get_initial() if 'email' in self.request.GET: initial['email'] = self.request.GET['email'] return initial def get_form(self, form_class=None): form = super(SignupView, self).get_form(form_class) if 'email' in self.request.GET and self.request.GET['email']: emailField = form.fields['email'] emailField.widget.attrs['readonly'] = True return form it is using the following form: class SignUpForm (forms.ModelForm): optin = forms.BooleanField( required=True, label = _('I agree with the Terms of Service and the Privacy Policy'), ) class Meta: model = get_user_model() fields = ('email', 'username',) labels = { 'username': _('Username'), 'email': _('Email'), } help_texts = { 'username': _('Your username, which may be seen publicly.'), 'email': _('A valid email address that will remain between us.') } error_messages = { 'username': { 'min_length': _("Your username needs to be at least 3-character long"), }, } def __init__(self, *args, **kwargs): super(SignUpForm, self).__init__(*args, **kwargs) self.fields['email'].required = True self.fields['username'].required = True self.fields['username'].min_length = 3 As you can see, nothing complicated. Yet, although it works well with GET requests, a POST request would hang in production (dockerized gunicorn + nginx) -- server 502. … -
Form preview in Django
I am building a registration form. Whenever a user fills the form and clicks the register button I want them to see the preview of their submissions. I am having problems with the arguments. Here goes my code: models.py from django.db import models from phonenumber_field.modelfields import PhoneNumberField # Create your models here. class Register(models.Model): regChoice = ( ('Self', 'Self'), ('Group', 'Group'), ('Corporate', 'Corporate'), ('Others', 'Others'), ) name = models.CharField(max_length=50) email = models.EmailField(max_length=254,null=True) phoneNumber = PhoneNumberField(null=True) idCard = models.ImageField(null=True) regType = models.CharField(max_length=25, choices=regChoice,null=True) ticketNo = models.IntegerField(default=1) def __str__(self): return self.name forms.py from django import forms from django.forms import ModelForm from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from .models import * class RegisterForm(ModelForm): name = forms.CharField(widget=forms.TextInput(attrs={'placeholder':'Your full name...'})) email = forms.CharField(widget=forms.TextInput(attrs={'placeholder':'Your email...'})) phoneNumber = forms.CharField(widget=forms.TextInput(attrs={'placeholder':'Your phone number...'})) class Meta: model = Register fields = '__all__' urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index, name='home'), path('preview.html/<str:pk>', views.preview, name="preview") ] views.py from django.shortcuts import render, redirect from .models import * from .forms import * # Create your views here. def index(request): form = RegisterForm() if request.method == 'POST': form = RegisterForm(request.POST, request.FILES) if form.is_valid(): form.save() context = {'form':form} return render(request, 'event/index.html', context) def preview(request, pk): reg = … -
Heroku godaddy custom domain name not working
It just shows the parking page. What am I doing wrong? -
Dynamic content colouring change base on events in Django
Is it possible to create two boxes simulated network devices and line connecting them simulating the actual network connection(attached picture) in my html template. And have them change colour from green to red upon certain events coming from views.py. Dynamic Boxes and line Let say I have the below simple code from views.py: snmpvalues = 'output taken from pysnmp' ### Code not included ### def netstat(request): for line in snmpvalues: if line == '1': return ('Green') ### Network is up ### else: return ('red') ### System is down ### Based on the above code. I want to change the colours of the two boxes and line from either green (Network is up) or red (Network is down). Can this be done? Your help is greatly appreciated as usual. -
Switching Bootstrap active nav links with jquery
I am trying to incorporate a jquery function to automatically change the active status of the nav links in my Bootsrap Navbar. I have a base HTML file which extends into an app-specific base file. That file is then extended to the individual pages navigated by the navbar. Here is the app-specific HTML: {% extends "base.html" %} {% load static %} {% block css %} <link rel="stylesheet" href="{% static 'home/main.css' %}"> {% endblock css %} {% block js %} <script> $(function() { $("#home-navs").click(function() { // remove classes from all $("#home-navs").removeClass("active"); // add class to the one we clicked $(this).addClass("active"); }); }); </script> {% endblock js %} {% block content %} <br> <div class="container status-update"> <div class="container"> <form> <div class="input-group-lg"> <input type="text" class="form-control" value="What's new?"> </div> <br style="height:20px"> <button type="submit" class="btn btn-primary btn-lg" name="button">Post</button> </form> </div> </div> <br> <div class="container"> <nav class="navbar navbar-expand-lg navbar-light" style="background-color: #6298bf"> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <div class="navbar-nav"> <a class="nav-link active" id="home-navs" href="{% url 'home' %}">Activity Feed</a> <a class="nav-link" id="home-navs" href="{% url 'vehicle-updates' %}">Vehicle Updates</a> <a class="nav-link" id="home-navs" href="/space.html">Garage Updates</a> </div> </div> </nav> </div> And then I have this in the head of my primary base.html file: {% load static %} <!doctype html> <html lang="en"> <head> <!-- … -
Populating a user field in the admin panel throws an AttributeError while rendering a template for the views
I'm developing a Q&A platform based on which a user can ask questions and others registered with the website can comment on a question asked. Comments can be added via a form in the template or the admin panel. I'm trying to populate the user field in the admin panel by default to show the username of the current registered user, which works fine. But however my view returns an AttributeError at /questions/1 'NoneType' object has no attribute 'user' when I try to view a question asked. Code admin.py from django.contrib import admin from . models import Question, Comments from .forms import CommentForm #Register your models here. class CommentsAdmin(admin.ModelAdmin): def get_form(self, request, obj=None, **kwargs): ModelForm = super(CommentsAdmin, self).get_form(request, obj, **kwargs) class ModelFormMetaClass(ModelForm): def __new__(cls, *args, **kwargs): kwargs['request'] = request return ModelForm(*args, **kwargs) return ModelFormMetaClass fields = (('question'), ('user'), ('content',),) form = CommentForm admin.site.register(Comments, CommentsAdmin) admin.site.register(Question) forms.py from django import forms from .models import Question, Comments from django.contrib.auth.models import User class CommentForm(forms.ModelForm): def __init__(self, *args, **kwargs): self.request = kwargs.pop('request', None) super(CommentForm, self).__init__(*args, **kwargs) self.fields['user'].initial = self.request.user class Meta: model = Comments fields= {'content'} views.py def viewQuestion(request, question_id): viewquestion=Question.objects.get(id=question_id) comments = Comments.objects.filter(question=viewquestion).order_by('-question_id') if request.method == "POST": comment_form = CommentForm(request.POST) if comment_form.is_valid(): content … -
Page not found (404) Request Method: POST Request URL: http://127.0.0.1:8000/login/login1
when i log in to my 'login' page , browser shows this error: Page not found (404) Request Method: POST Request URL: http://127.0.0.1:8000/login/login1 Using the URLconf defined in webapp.urls, Django tried these URL patterns, in this order: 1.admin/ 2.Home/ [name='Home'] 3.login/ [name='login'] 4.Signup/ [name='Signup'] 5.login1/ [name='login1'] The current path, login/login1, didn't match any of these. here's login.html file: Student Login Form <form method="post" action='login1'> {% csrf_token %} <h1 style="color:red"> {{ error}} </h1> <div class="container"> <label>Username : </label> <input type="text" placeholder="Enter Username" name="username" required> <label>Password : </label> <input type="password" placeholder="Enter Password" name="pass" required> <button type="submit">Login</button> <input type="checkbox" checked="checked"> Remember me <button type="button" class="cancelbtn"> Cancel</button> <a href="{% url 'Signup' %}"> SignUp </a> </div> </form> here's urls.py: from django.contrib import admin from django.urls import path from application import views urlpatterns = [ path('admin/', admin.site.urls), path('Home/', views.Home , name = "Home"), path('login/', views.login,name = 'login'), path('Signup/', views.Signup , name = 'Signup'), path('login1/',views.login1,name='login1'), ] here's views.py: def login(request): return render(request, 'login.html') def login1(request): if request.method == "POST": uname = request.POST['username'] pwd = request.POST['pass'] user = auth.authenticate(username=uname, password=pwd) if user is not None: auth.login(request, user) return render(request, 'Home.html') else: return render(request, 'login.html', {'error': 'invalid credential details'}) else: return render(request, 'Signup.html') kindly answer asap. -
Firebase_admin Auth The default Firebase app already exists. Django
I want to use firebase_admin auth in django,but when i try this code import firebase_admin from firebase_admin import credentials from firebase_admin import auth user = auth.get_user_by_email('myemail') print('Successfully fetched user data: {0}'.format(user.uid)) it said 'The default Firebase app already exists. This means you called ' ValueError: The default Firebase app already exists. This means you called initialize_app() more than once without providing an app name as the second argument. In most cases you only need to call initialize_app() once. But if you do want to initialize multiple apps, pass a second argument to initialize_app() to give each app a unique name. Log Exception in thread django-main-thread: Traceback (most recent call last): File "c:\programdata\anaconda3\lib\threading.py", line 926, in _bootstrap_inner self.run() File "c:\programdata\anaconda3\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\Users\Boss\Envs\pyweb\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\Boss\Envs\pyweb\lib\site-packages\django\core\management\commands\runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "C:\Users\Boss\Envs\pyweb\lib\site-packages\django\core\management\base.py", line 395, in check include_deployment_checks=include_deployment_checks, File "C:\Users\Boss\Envs\pyweb\lib\site-packages\django\core\management\base.py", line 382, in _run_checks return checks.run_checks(**kwargs) File "C:\Users\Boss\Envs\pyweb\lib\site-packages\django\core\checks\registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "C:\Users\Boss\Envs\pyweb\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config return check_resolver(resolver) File "C:\Users\Boss\Envs\pyweb\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\Users\Boss\Envs\pyweb\lib\site-packages\django\urls\resolvers.py", line 407, in check for pattern in self.url_patterns: File "C:\Users\Boss\Envs\pyweb\lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = … -
How to use Django Backend Permissions in React Frontend?
I am implementing a simple object level permission using the django rest api backend and react.js frontend. I can successfully restrict the permission to a specific component in my backend by granting object-level permissions. class PostOwnerPermssion(permissions.BasePermission): """ Custom permission to only allow authors of a story to edit it """ def has_object_permission(self, request, view, obj): # Read permissions are allowed to any request, # so we'll always allow GET, HEAD or OPTIONS requests. if request.method in permissions.SAFE_METHODS: return True # Write and Delete permissions are only allowed to the owner of the story. return obj.author == request.user Now I want to hide some options in my react frontend based on the object-level permissions I granted in my backend. More concretely, a user other than the author should not see the "Edit Story" option in my frontend. I found this answer that looks quiet promissing but i have problems to map it to my example. How do I get the permission list of the user? In my backend only the author of story can edit the story. How can i pass this information from my django backend to my react frontend? So that i can work within React / Redux with … -
Collect static error while deploying django project to heroku
I am trying to finish a youtube tutorial by Dennis Ivy and while deploying to heroku get the following error. Already hooked static and database to AWS. remote: -----> $ python manage.py collectstatic --noinput remote: Traceback (most recent call last): remote: File "manage.py", line 15, in <module> remote: execute_from_command_line(sys.argv) remote: File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line remote: utility.execute() remote: File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/__init__.py", line 395, in execute remote: self.fetch_command(subcommand).run_from_argv(self.argv) remote: File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/base.py", line 328, in run_from_argv remote: self.execute(*args, **cmd_options) remote: File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/base.py", line 369, in execute remote: output = self.handle(*args, **options) remote: File "/app/.heroku/python/lib/python3.7/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 187, in handle remote: collected = self.collect() remote: File "/app/.heroku/python/lib/python3.7/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 113, in collect remote: handler(path, prefixed_path, storage) remote: File "/app/.heroku/python/lib/python3.7/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 338, in copy_file remote: if not self.delete_file(path, prefixed_path, source_storage): remote: File "/app/.heroku/python/lib/python3.7/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 248, in delete_file remote: if self.storage.exists(prefixed_path): remote: File "/app/.heroku/python/lib/python3.7/site-packages/storages/backends/s3boto3.py", line 562, in exists remote: self.connection.meta.client.head_object(Bucket=self.bucket_name, Key=name) remote: File "/app/.heroku/python/lib/python3.7/site-packages/botocore/client.py", line 316, in _api_call remote: return self._make_api_call(operation_name, kwargs) remote: File "/app/.heroku/python/lib/python3.7/site-packages/botocore/client.py", line 599, in _make_api_call remote: api_params, operation_model, context=request_context) remote: File "/app/.heroku/python/lib/python3.7/site-packages/botocore/client.py", line 645, in _convert_to_request_dict remote: api_params, operation_model, context) remote: File "/app/.heroku/python/lib/python3.7/site-packages/botocore/client.py", line 677, in _emit_api_params remote: params=api_params, model=operation_model, context=context) remote: File "/app/.heroku/python/lib/python3.7/site-packages/botocore/hooks.py", line 356, in emit remote: return self._emitter.emit(aliased_event_name, **kwargs) remote: … -
Model Formset dynamic delete fields not saving the form
Here, I have used a modelformset where i added a jquery to add and delete fields dynamically. When i try to add multiple items it works and saves the data as well but when i delete a field the rest of the fields after the delete field does not get save. The problem here is only when adding the form. The code works fine when editing the form. Here, i am using the same template the render both add and edit form. This is my contentAdd.html page <script type="text/javascript"> function updateElementIndex(el, prefix, ndx) { var id_regex = new RegExp('(' + prefix + '-\\d+)'); var replacement = prefix + '-' + ndx; if ($(el).attr("for")) $(el).attr("for", $(el).attr("for").replace(id_regex, replacement)); if (el.id) el.id = el.id.replace(id_regex, replacement); if (el.lecture_title) el.lecture_title = el.lecture_title.replace(id_regex, replacement); if (el.lecture_content) el.lecture_content = el.lecture_content.replace(id_regex, replacement); if (el.youtube_url) el.youtube_url = el.youtube_url.replace(id_regex, replacement); } $(document).ready(function () { function updateEmptyFormIDs(element, totalForms){ var thisInput = element // get current form input name var currentName = element.attr('name') // replace "prefix" with actual number var newName = currentName.replace(/__prefix__/g, totalForms) // console.log(newName) // update input with new name thisInput.attr('name', newName) thisInput.attr('id', "id_" + newName) // create a new form row id var newFormRow = element.closest(".form-row"); var newRowId = … -
Python social auth custom pipeline asking when it is not supposed to
I created a custom pipeline for Python Social auth and when already registered social user clicks on auth link, my pipeline is invoked that it is not supposed to. So I have the following model: class Profile(UUIDMixin): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="profile") avatar = models.ImageField(upload_to="profile", blank=True) age = models.PositiveIntegerField(choices=AgeVariation.choices) gender = models.CharField(max_length=1, choices=Gender.choices) and my custom pipeline purpose is to create user profile during the very first authentication. And view handles it's create logic. @partial def profile_creation(strategy, details, user=None, *args, **kwargs): if user is None: user = User.objects.get(is_active=True, email=details.get("email", kwargs.get("email"))) try: profile = user.profile except Profile.DoesNotExist: print("PROFILE does not exist") current_partial = kwargs.get("current_partial") return strategy.redirect(f"{reverse('account:profile_form')}?partial_token={current_partial.token}") if profile: return {"profile": profile, "user": user} Can anyone tell me where I did wrong? -
Django how to filter nested relationships
I have these two models class Assignment(models.Model): subject_info = models.ForeignKey(SubjectInfo, on_delete=models.CASCADE, related_name='assignments') release_results = models.BooleanField(default=False) total_marks = models.IntegerField(default=0) deadline = models.DateTimeField() class StudentAssignment(models.Model): assignment = models.ForeignKey(Assignment, on_delete=models.CASCADE, related_name='submissions') student = models.ForeignKey(Student, on_delete=models.CASCADE) submitted = models.BooleanField(default=False) scored = models.BooleanField(default=False) status = models.CharField(choices=STATUS, max_length=50, null=True, blank=True) score = models.IntegerField(null=True, blank=True) In my view I am trying to get all assignments that either: 1) Don't have a studentassignment attribute 2) Have a studentassignment attribute but the submitted attribute is False I did it like this: def get_queryset(self, *args, **kwargs): queryset = Assignment.objects.filter( subject_info__teacher__school=self.request.user.student.school, subject_info__related_class=self.request.user.student.current_class, subject_info__subject__in=self.request.user.student.subjects, deadline__gte=datetime.now(), ).exclude( submissions__isnull=True, submissions__student=self.request.user.student, submissions__submitted=False, ) return queryset But it is not returning correct values. How can I fix this, please? -
The `request` argument must be an instance of `django.http.HttpRequest`, not `builtins.int`
I have an app in django, which is for API created exactly as this article says. I have 3 functions in a views.py of an app. Here is my urls.py from django.contrib import admin from django.urls import path from django.conf.urls import url from apis_folder import views as stack_views urlpatterns = [ path('admin/', admin.site.urls), url('not_so_complex_api/', stack_views.not_so_complex_api), url('simple_api/', stack_views.simple_api), url('complicated_api/', stack_views.complicated_api) ] Here is how my views look like: from django.shortcuts import render from django.http import Http404 from rest_framework.views import APIView from django.urls import path from rest_framework.decorators import api_view from rest_framework.response import Response from rest_framework import status from django.http import JsonResponse from django.core import serializers from django.conf import settings from datetime import datetime from ast import literal_eval from json import loads as json_loads from psycopg2 import connect, errors @api_view(["POST"]) def simple_api(subject_data): # this api takes a dictionary and make a simple math calculation and returns result as JsonResponse return JsonResponse(simple_result, safe=False) @api_view(["POST"]) def not_so_complex_api(patient_data): # this api takes a dictionary, then queries a remote postgresql database single time # and then make a simple math calculation and returns result as JsonResponse return JsonResponse(not_so_complicated_result, safe=False) @api_view(["POST"]) def complicated_api(subject_data_risk): # this api takes a dictionary as input, then queries a remote postgresql database many … -
Django Simple Captcha Refresh Audio Source
https://github.com/mbi/django-simple-captcha After following How to create Ajax refresh for django-simple-captcha and getting the captcha to refresh with a Refresh link, how do you refresh the audio src? Tried combining this code with the ajax refresh code above: var audio = document.getElementById('audio'); audio.load(); Custom_field.html: {% load i18n %} {% spaceless %} <label class="control-label">{{ label }}</label> <img src="{{ image }}" alt="captcha" class="captcha" /> <br/> <audio id="audio" class="w-100 mt-2" controls> <source id="audioSource" src="{{ audio }}" /> </audio> {% include "django/forms/widgets/multiwidget.html" %} {% endspaceless %} -
Adding multiple database in Django project
I tried maybe 100 samples but multiple database never worked in my projects. Please help me. I have tired more codes from various sites, but there is last codes in my project which I got from official website. All is the same with the Documentation but still not working. Settings.py DATABASE_ROUTERS = ['MyApp.routers.TenantRouter'] DATABASE_APPS_MAPPING = {'tenant': 'tenant'} DATABASES = { 'default': { 'NAME': 'host_data', 'ENGINE': 'django.db.backends.mysql', 'USER': 'root', 'PASSWORD': '******' }, 'tenant': { 'NAME': 'tenant_data', 'ENGINE': 'django.db.backends.mysql', 'USER': 'root', 'PASSWORD': '******' } } Routers.py class TenantRouter: route_app_labels = {'tenant'} def db_for_read(self, model, **hints): if model._meta.app_label in self.route_app_labels: return 'tenant_data' return None def db_for_write(self, model, **hints): if model._meta.app_label in self.route_app_labels: return 'tenant_data' return None def allow_relation(self, obj1, obj2, **hints): if ( obj1._meta.app_label in self.route_app_labels or obj2._meta.app_label in self.route_app_labels ): return True return None def allow_migrate(self, db, app_label, model_name=None, **hints): if app_label in self.route_app_labels: return db == 'tenant_data' return None OneApp/models.py class UserTbl(models.Model): username = models.CharField(max_length=50) class Meta: app_label = 'tenant' db_table = u'UserTbl' And using below line for migrate. But not migrating anything. It always says No migrations to apply. python3 manage.py migrate --database=tenant -
How to load api token from .env file in js function in template of python?
I had created an .env file at project root and I specified the api_token in the file I want to use that token in js function which is specified in template the js function is: var mData = new FormData(); mData.append('token','my_token'); mData.append('channel', id); mData.append('text',input); mData.append('as_user', 'true'); In the place of my_token I want to get the token from .env file In .env file I stored like this API_KEY= "my key" -
d3.js Molecule Diagram only working on the last element of the object
so I'm trying to create a visual representations of a couple of vlans and the connections of switches in each of them. I tried implementing it with this example I found online https://bl.ocks.org/mbostock/3037015 , the problem is that when i created a loop to go through all of the vlans, only the last vlan is drawn, there's really no reason I can see of why this is happening since all elements are calling the function code: var data = {{ graph_vlans | safe }}; console.log(data); $(document).ready(() => { //----------------------------------------------------------------- // TREE DISPLAY --------------------------------------------------- //----------------------------------------------------------------- var toggler = document.getElementsByClassName("caret"); for (var i = 0; i < toggler.length; i++) { toggler[i].addEventListener("click", function () { this.parentElement.querySelector(".nested").classList.toggle("active"); this.classList.toggle("caret-down"); }); } //----------------------------------------------------------------- // NETWORK DIAGRAM ------------------------------------------------ //----------------------------------------------------------------- var width = 960, height = 500; var color = d3.scale.category20(); var radius = d3.scale.sqrt().range([0, 6]); var i = 0; for (var key in data) { console.log(key); console.log(key["4"]); var svg = d3.select("#graph_" + key).append("svg").attr("width", width).attr("height", height); var force = d3.layout.force() .size([width, height]) .charge(-400) .linkDistance(function (d) { return radius(d.source.size) + radius(d.target.size) + 20; }); var graph = data[key]; var link = svg.selectAll(".link") .data(graph.links) .enter().append("g") .attr("class", "link"); link.append("line") .style("stroke-width", function (d) { return (d.bond * 2 - 1) * 2 … -
django two selection option relation
I have this two selected option in my html, for example: if the student selected the Incoming Grade 11 from public the selected of the Education level show grade 11 and if the student selected the Incoming Grade 12 from public the selected of the Education level show grade 11 <select name="studenttype" id="studenttype"> <option >- Student Type -</option> {% for student_type in cat %} <option value="{{student_type.id}}" name="studenttype" style="text-transform: capitalize; border-radius: 8px 8px 8px 8px ; width: auto;" class="slide-in-bottom">{{student_type.Student_types}}</option> {% endfor %} </select> <select name="gradelevel" id="gradelevel"> <option class="slide-in-bottom" class="tracking-in-expand">-- Education Level --</option> {% for ylvl in edulevel %} <option value="{{ylvl.id}}">{{ylvl.Description}}</option> {% endfor %} </select> is there any possible to achieve this functionality using javascript? and if yes, can you show me an example using my code??