Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django server-side and client-side pagination with Datatables
This might sound like a stupid question so apologies in case I'm wasting your time. I have a tons or results coming from my data in my Django project. It's a table with many columns and almost 4000 rows. I am using Datatables for pagination, filtering, horizontal scrolling, sorting the columns. Client-side I am also using django-filter for querying the database. My problem is that the loading of the initial data (non filtered via django-filter) takes a lot of time. Shall I implement pagination on the client-side? If so, how does this work with Datatables? Will Datatables paginate/display only the (first page of) paginated data coming from the server-side query? Is there a way for the two to work together? Thanks. -
How to pass parameter to javascript from Django template while using for loop
I am creating a quiz application using django. I am facing a problem in sending paramter to my javascript function from django template. Html Code. {% for qts in page %} <input type="button" id ="btn-1" name="grp" value="{{qts.opt1}}" class="btn btn-outline-primary mt-3" onclick = "check(this,{{qts.answer}})"> Javascript Code function check(btn,answer) { var user_ans_id = btn.id; var user_ans = document.getElementById(user_ans_id).value; console.log(answer); } Is there any other solution -
passing instance to Django modal form
I want to do edit on a modal pop up form, edit is working but cant see the existing instance, how I can do it? any help is appreciated. Here I have passed the form as below class DomainListView(ListView): model = Domain template_name = 'super_admin/domain_list.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) form = DomainEditForm(self.request.POST or None) context['form'] = form return context and the template is as follows <div class="modal fade" id="domain-edit-{{ item.pk }}"> <div class="modal-dialog" role="document"> <form class="form-valide" action="{% url 'domain_edit' item.pk %}" method="POST" id="" enctype="multipart/form-data"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title"> Edit Domain </h5> <button type="button" class="close" data-dismiss="modal"><span>&times;</span> </button> </div> <div class="modal-body"> <div class="basic-form"> <div class="form-group"> {% csrf_token %} {{ form.errors }} {{ form | crispy }} </div> </div> </div> <div class="modal-footer"> <button type="submit" class="btn btn-primary">submit</button> </div> </div> </form> </div> </div> this is inside for loop along with list items, I tried to fetch the instance as follows in get context data override, but it gives key error def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) obj = get_object_or_404(Domain, kwargs={'pk': self.kwargs['pk']}) form = DomainEditForm(self.request.POST or None, instance=obj) context['form'] = form return context -
Page not found (404) djano project
Here is my code i tried it but i get a error 'accounts/register' could not be found index.html {% load static %} {% static "images" as baseUrl %} <!doctype html> <!-- Website Template by freewebsitetemplates.com --> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Mustache Enthusiast</title> <link rel="stylesheet" type="text/css" href="{% static 'css/style.css' %}"> <link rel="stylesheet" type="text/css" href="{% static 'css/mobile.css' %}" media="screen and (max-width : 568px)"> <script type="text/javascript" src="{% static 'js/mobile.js' %}"></script> </head> <body> <div id="header"> <a href="{% static 'index.html' %}" class="logo"> <img src="{% static 'images/logo.jpg' %}" alt=""> </a> <ul id="navigation"> <li class="selected"> <a href="{% static 'index.html' %}">home</a> </li> <li> <a href="{% static 'about.html' %}">about</a> </li> <li> <a href="{% static 'accounts/register' %}">register</a> </li> <li> <a href="{% static 'contact.html' %}">contact</a> </li> </ul> </div> <div id="body"> <div id="featured"> <img src="{% static 'images/the-beacon.jpg' %}" alt=""> <div> <h2>the beacon to all mankind</h2> <span>Our website templates are created with</span> <span>inspiration, checked for quality and originality</span> <span>and meticulously sliced and coded.</span> <a href="{% static 'blog-single-post.html' %}" class="more">read more</a> </div> </div> <ul> {% for cate in categos %} <li> <a href="{% static 'gallery.html' %}"> <img src="{{cate.img.url}}" alt="" style="width:240px;height:200px;"> <span>{{cate.name}}</span> </a> </li> {% endfor %} </ul> </div> </body> </html> register.html {% load static%} <!doctype html> <!-- Website Template by … -
Condition setting problem over custom build decorator in Django
I am trying to make a custom build decorator in Django. my models.py: class myCustomeUser(AbstractUser): id = models.AutoField(primary_key=True) username = models.CharField(max_length=20, unique="True", blank=False) password = models.CharField(max_length=20, blank=False) is_Inspector = models.BooleanField(default=False) is_Industry = models.BooleanField(default=False) is_Admin = models.BooleanField(default=False) def __str__(self): return self.username class Inspector(models.Model): user = models.ForeignKey(myCustomeUser, on_delete=models.CASCADE, related_name='inspector_releted_user') name = models.CharField(max_length=200, blank=False, null=True) gmail = models.EmailField(null=True, blank=False, unique=True) nid = models.IntegerField(blank=False, unique=True) inspector_varified = models.BooleanField(default=False, blank=True, null=True) def __str__(self): return self.name Now I want to build a decorator that will allow the user to pass by satisfying the following 3 conditions: user is active and logged in is_Inspector value is True inspector_varified's value is also True (inspector_varified is in under Inspector class) my decorators.py: def inspector_required(function=None, redirect_field_name=REDIRECT_FIELD_NAME, login_url='app2:request_login'): actual_decorator = user_passes_test( lambda u: u.is_active and u.is_Inspector, login_url=login_url, redirect_field_name=redirect_field_name ) if function: return actual_decorator(function) return actual_decorator It is maintaining conditions 1 & 2, but condition-3 is not satisfied by it. How can I code for it also? -
AttributeError: 'list' object has no attribute 'order_by' Python
I was trying to combine two queryset objects data by itertools chain python predefine function and sorting this with order_by. but i'm getting an AttributeError: 'list' object has no attribute 'order_by'. If anybody could figure out where i'm doing thing wrong then would be much appreciated. thank you so much in advance. try: qs = ChatMessage.objects.filter( Q(from_user=user, to_user=to_user) | Q(from_user=to_user, to_user=user) ) except: raise ValidationError({"message":"bad request"}) data = UserChatMessageSerializer(qs, many=True, context={'request': request}).data # qs.update(read_status=True) for record in data: data1 = record['conversation'] data2 = record['files'] print(data2) from itertools import chain all_results = list(chain(data1,data2)).order_by('created_on') -
Django DayArchiveview is not detected in urls.py
I created several date-based views in Django, and while views for year and month function as expected, the view to display days is not detected. For instance, if I try to get http://127.0.0.1:8000/blog/archive/2021/, or http://127.0.0.1:8000/blog/archive/2021/01 the views will be displayed, http://127.0.0.1:8000/blog/archive/2021/01/07 will fail. I understand that the problem must be with urls.py configuration, but I just cannot find it in documentation. I also tried passing day_format='%d' to as_view method, without any results. urls.py from django.urls import path, re_path from blog import views app_name = 'blog' urlpatterns = [ # Example: /blog/ path('', views.PostListView.as_view(), name='index'), # Example: /blog/post/ (same as /blog/) path('post/', views.PostListView.as_view(), name='post_list'), # Example: /blog/post/django-example/ re_path(r'^post/(?P<slug>[-\w]+)/$', views.PostDetailView.as_view(), name='post_detail'), # Example: /blog/archive/ path('archive/', views.PostArchiveView.as_view(), name='post_archive'), # Example: /blog/archive/2019/ path('archive/<int:year>/', views.PostYearArchiveView.as_view(), name='post_year_archive'), # Example: /blog/archive/2019/nov/ path('archive/<int:year>/<int:month>/', views.PostMonthArchiveView.as_view(month_format='%m'), name='post_month_archive'), # Example: /blog/archive/2019/nov/10/ path('archive/<int:year>/<str:month>/<int:day>/', views.PostDayArchiveView.as_view(), name='post_day_archive'), # Example: /blog/archive/today/ path('archive/today/', views.PostTodayArchiveView.as_view(), name='post_today_archive'), ] views.py from django.shortcuts import render # Create your views here. from django.views.generic import ListView, DetailView, ArchiveIndexView, YearArchiveView, MonthArchiveView, \ DayArchiveView, TodayArchiveView from blog.models import Post class PostListView(ListView): model = Post template_name = 'blog/post_all.html' context_object_name = 'posts' paginate_by = 2 class PostDetailView(DetailView): model = Post class PostArchiveView(ArchiveIndexView): model = Post date_field = 'modify_dt' class PostYearArchiveView(YearArchiveView): model = Post date_field = 'modify_dt' … -
Django + html/css/Jinja vs Django + React
I'm trying to develop a simple neat website with a second page that has a python application. So far, I'm using Django with html/css/Jinja to make the website. The application works fine, but I'm finding simple styling things like making a nav bar and even anchoring internal links incredibly difficult. I find the combination of Jinja with CSS overly complex, and most the time things don't work for me. Definitely a case of me needing to study more into django, but I feel it shouldn't be this difficult to get simple things to work. Opinion of jinja/css aside, if I use React to cover the front end is it possible to avoid using the jinja/css combo? Should I invest my time to struggle through the css/jinja stuff, or would React knowledge be more valuable? Thanks, Sad_man -
'django.db.utils.IntegrityError: UNIQUE constraint failed:' error still showing after i have deleted the attribute
I was trying to add an attribute to a django model and it showed me 'django.db.utils.IntegrityError: UNIQUE constraint failed:' error. So i backed down and just deleted the attribute, but it still shows me the error, so please how can i delete the attribute permanently. -
Using django form within custom html template
I have a html file that I wanna use this template to render my form and save it to my database How to do this? HTML code: <div class="container-contact100"> <div class="wrap-contact100"> <form class="contact100-form validate-form" enctype="multipart/form-data" method="POST"> {% csrf_token %} <span class="contact100-form-title"> Add Item! </span> <div class="wrap-input100 validate-input" data-validate="Name is required"> <span class="label-input100">Title</span> <input class="input100" type="text" name="name" placeholder="Enter food name"> <span class="focus-input100"></span> </div> <div class="wrap-input100 validate-input"> <span class="label-input100">Price</span> <input class="input100" type="number" name="price" placeholder="Enter food price"> <span class="focus-input100"></span> </div> <div class="wrap-input100 validate-input" data-validate = "Message is required"> <span class="label-input100">Description</span> <textarea class="input100" name="message" placeholder="Your description here..."></textarea> <span class="focus-input100"></span> </div> <div class="wrap-input100 validate-input" data-validate="Image is required"> <input type="file" class="custom-file-input" id="customFile" name="filename"> <label class="custom-file-label" for="customFile">Choose file</label> <span class="focus-input100"></span> </div> <div class="container-contact100-form-btn"> <div class="wrap-contact100-form-btn"> <div class="contact100-form-bgbtn"></div> <button class="contact100-form-btn" type="submit"> <span> Add <i class="fa fa-long-arrow-right m-l-7" aria-hidden="true"></i> </span> </button> </div> </div> </form> </div> </div> <div id="dropDownSelect1"></div> and here is my forms.py : from django import forms from .models import Product class AddItemForm(forms.ModelForm): class Meta: model = Product fields = '__all__' even you can access my project from this link via github: https://github.com/imanashoorii/FoodMenu.git -
django check-contraint boolean expression [postgresql]
So I have a model like this class Role(BaseModel): class Meta: verbose_name = 'role' verbose_name_plural = 'roles' ordering = ['position', 'cluster'] required_db_features = { 'supports_deferrable_unique_constraints', } constraints = [ models.UniqueConstraint( fields=['position', 'cluster'], name='deferrable_unique_role_position', deferrable=models.Deferrable.DEFERRED ), models.CheckConstraint( name='default_role_check', check=models.Q( is_default=True, position=1, color='#969696', name='@everyone' ) ) ] permission_flags = [ 'READ_DATA', 'WRITE_DATA', 'MANAGE_RECORDS', 'MANAGE_ROLES', 'MANAGE_CLUSTER', 'MANAGE_DATASHEETS', 'MANAGE_FIELDS', 'MANAGE_CONSTRAINTS', 'KICK_MEMBERS', 'MANAGE_MEMBERS', ] default_perm_flags = ['READ_DATA', 'WRITE_DATA', 'MANAGE_RECORDS'] def __str__(self): return self.name objects = managers.RolesManager() positions = managers.PositionalManager() permissions = BitField(flags=permission_flags, default=default_perm_flags, db_index=True) position = models.PositiveSmallIntegerField(null=True, blank=True, db_index=True, editable=True) name = models.CharField(max_length=100, validators=[MinLengthValidator(2)], db_index=True, default='new role') color = ColorField(db_index=True, default='#969696') is_default = models.BooleanField(default=False, db_index=True) cluster = models.ForeignKey('api_backend.Cluster', on_delete=models.CASCADE, editable=False) Basically I want to enforce a check constraint on this model such that when the model has the is_default field set to True, the name must always be @everyone the color must always be #969696 the position must always be 1. I tried to implement the same, however my current implementation doesn't work. While using serializers, I can edit the default role's name, and no exceptions are raised. I am using postgresql at the backend. Can someone please help me? thanks in advance! -
How to make the LINE message API access token change dynamically on request
I want to use django to change the access token of the LINE message API depending on the request. However, the decorator is not reflected because the handler is declared in the post function. How can I set the handler? In order to change the access token dynamically, I must receive a request. from django.shortcuts import render from django.http import HttpResponseForbidden, HttpResponse from django.views.decorators.csrf import csrf_exempt from linebot import (LineBotApi, WebhookHandler) from linebot.exceptions import (InvalidSignatureError) from linebot.models import ( MessageEvent, TextMessage, TextSendMessage, ) import os from user_app.models import Profile from django.views import View class Api(View): @csrf_exempt def post(self, request, *args, **kwargs): YOUR_CHANNEL_ACCESS_TOKEN = "22222222222222" ←Change dynamically on request YOUR_CHANNEL_SECRET = "11111111111111111111"Change dynamically on request line_bot_api = LineBotApi(YOUR_CHANNEL_ACCESS_TOKEN) handler = WebhookHandler(YOUR_CHANNEL_SECRET) signature = request.META['HTTP_X_LINE_SIGNATURE'] body = request.body.decode('utf-8') try: handler.handle(body, signature) except InvalidSignatureError: HttpResponseForbidden() return HttpResponse('OK', status=200) @handler.add(MessageEvent, message=TextMessage) def handle_text_message(event): print("dddd") line_bot_api.reply_message(event.reply_token, TextSendMessage(text=event.message.text)) -
How to work with multiple databases in Django [using Database Routers]
I need to isolate django`s default (auth, contenttypes, sessions) apps database, I read in documentation [Multiple Databses][1] all is clear and well explained, but not working to me :( settings.py DATABASES = { 'default_django': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', }, 'default': { 'ENGINE': 'django.contrib.gis.db.backends.postgis', 'OPTIONS': { 'options': '-c search_path=eos,public' }, 'NAME': '****', 'USER': '*****', 'PASSWORD': '****', 'HOST': 'localhost', 'PORT': '5432', } } DATABASE_ROUTES = ['core.dbrouter.AuthRoute', 'core.dbrouter.GisRoute'] and ./core/dbrouter.py class AuthRouter: """ A router to control all database operations on models in the 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', """ route_app_labels = { 'auth', 'admin', 'contenttypes', 'sessions', 'messages', 'staticfiles' } def db_for_read(self, model, **hints): """ Attempts to read auth and contenttypes models go to auth_db. """ if model._meta.app_label in self.route_app_labels: return 'default_django' return None def db_for_write(self, model, **hints): """ Attempts to write auth and contenttypes models go to auth_db. """ if model._meta.app_label in self.route_app_labels: return 'default_django' return None def allow_relation(self, obj1, obj2, **hints): """ Allow relations if a model in the auth or contenttypes apps is involved. """ 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): """ Make sure the auth and contenttypes apps only appear in … -
Simple search in django-cms
I'm trying to implement a simple search in Django-cms (search article by title and description). The description field is a Django-cms Placeholder and I can't access its content. Any suggestion on how to do this? The model: class Article(models.Model): title = models.CharField(max_length=200) intro = models.TextField(max_length=300, blank=True) description = PlaceholderField('description') The view: from .models import Article from django.db.models import Q class ArticlesListView(generic.ListView): template_name = 'article/index.html' def get_queryset(self): search_string = self.request.GET.get('search', None) #search within title #result = Article.objects.filter(Q(title__icontains=search_string)) # works as expected #search within title and content # error: "Related Field got invalid lookup: icontains" result = Article.objects.filter(Q(title__icontains=search_string) | Q(description__icontains=search_string)) return result (django 3.0.11, django-cms 3.7.4, Python 3.7.8) -
How to raise different messages when the ValidationError is caused due to max_length limit and min_length limit in Django
I want to create a model in Django where I could introduce character values for a given field (task), with min_limit=1 and max_limit=255. The code would be something like this in the models.py file: from django.db import models from django.core.validators import MinLengthValidator, MaxLengthValidator from django.forms import ModelForm class ListModel(models.Model): task = models.CharField(max_length= 255, validators = [MinLengthValidator(1), MaxLengthValidator(255)]) status = models.BooleanField(default=False) class ListForm(ModelForm): class Meta: model = ListModel fields = ["task", "status"] Now, if the form is not valid I want to show different messages depending on whether it is invalid because of max_length>255 or because of min_length<1, the code would be something like this in the views.py file: from django.shortcuts import render, redirect from django.contrib import messages from django.http import HttpResponseRedirect from django.urls import reverse from .models import ListModel, ListForm def index(request): if request.method == 'POST': form = ListForm(request.POST) if form.is_valid(): form.save() alltasks = ListModel.objects.all() return HttpResponseRedirect(reverse("index")) else: if max_length > 255: messages.info(request, ('Maximum length limit: 255 characters!')) else: messages.info(request, ('No Task added!') return redirect('index') else: alltasks = ListModel.objects.all() return render(request, "index.html", {'alltasks': alltasks}) Now the problem is that the above code is giving the error name 'max_length' is not defined which is quite obvious as in views.py I have … -
django Page not found (404) forms
i'm building a simple app using django and i got this error when i'm making an authentication here is the error Page not found (404) Request Method: GET Request URL: http: / /localhost:8000/POST?csrfmiddlewaretoken=AZSGUVU7Z13xZoSOsuvFrSPDGy1ZXfHjeJtpHW3HCByK4We0fyLTihcIJsUKUKjt&username=a2020&password1=123456&password2=123456 here is views.py from django.shortcuts import render,redirect from django.contrib.auth.forms import UserCreationForm from django.contrib.auth import login def home(request): return render(request,'home.html') def signup(request): if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): user = form.save() login(request,user) return redirect('home') else: form = UserCreationForm() return render(request,'signup.html',{'form':form}) here is urls.py from django.urls import path,include from . import views urlpatterns = [ path('',views.home,name="home"), path('signup',views.signup,name="signup") ] -
Django 3 NameError: name 'model_name' is not defined
I know this question has come up but many answers refer to older versions of Django and Python. I am running Django 3 and Python 3. Besides in our project we have decided to separate each model in its own file under a "models" folder. Please see below our tree structure: ├── db.sqlite3 ├── manage.py ├── poi │ ├── admin.py │ ├── apps.py │ ├── CHANGELOG.md │ ├── fabfile.py │ ├── __init__.py │ ├── LICENSE │ ├── migrations │ │ ├── 0001_initial.py │ │ ├── 0002_auto_20210104_1048.py │ │ ├── __init__.py │ │ └── __pycache__ │ │ ├── 0001_initial.cpython-38.pyc │ │ ├── 0002_auto_20210104_1048.cpython-38.pyc │ │ └── __init__.cpython-38.pyc │ ├── models │ │ ├── __init__.py │ │ ├── layer.py │ │ ├── poi.py │ │ ├── __pycache__ │ │ │ ├── __init__.cpython-38.pyc │ │ │ ├── layer.cpython-38.pyc │ │ │ ├── poi.cpython-38.pyc │ │ │ └── tag.cpython-38.pyc │ │ └── tag.py │ ├── models.py In our models/init.py we have: from .poi import Poi from .tag import Tag from .layer import Layer In our models/poi/poi.py we have: from django.db import models from .tag import Tag from .layer import Layer class Poi(models.Model): ... ... tags = models.ManyToManyField('Tag', through='Layer') def __str__(self): return self.name In our … -
how to filter year from datefield in django
Basically I want to use 'chartjs' for display "Clustered Bar chart", with following things year wise Total amount Amount Received Amount Left I want to fetch data from data base and display it on chart, I have saved data of all above field 3 fields in one table for each date and I want to also fetch year from Datefield. Main things is how to display Clustered bar chart by fetching data from database for each year. class Allinvoice(models.Model): company_choice = ( ('VT_India', 'VT_India'), ('VT_USA', 'VT_USA'), ) company = models.CharField( max_length=30, blank=True, null=True, choices=company_choice) customer = models.ForeignKey(Customer, on_delete=models.CASCADE) project = models.ForeignKey(Allproject, on_delete=models.CASCADE) invoice_title = models.CharField(max_length=15) invoice_id = models.IntegerField(primary_key=True) currency = models.ForeignKey(Currency, on_delete=models.CASCADE) invoice_amount = models.IntegerField() invoice_date = models.DateField( blank=True, null=True) invoice_duedate = models.DateField( blank=True, null=True) invoice_description = models.TextField() def __str__(self): return str(self.invoice_id) class Paymentdete(models.Model): payment_id = models.IntegerField(primary_key=True) invoice = models.ForeignKey( Allinvoice, on_delete=models.CASCADE) total_amount = models.IntegerField() amountreceived = models.IntegerField() amount_left = models.IntegerField() currency = models.ForeignKey(Currency, on_delete=models.CASCADE, null=True) date = models.DateField( blank=True, null=True) paymentmethod = models.ForeignKey( Allpaymentmethod, on_delete=models.CASCADE) def __str__(self): return str(self.payment_id) So, above is the code of my 2 models.So, i want to get total of all data yearwise for example for year 2019= Total Amount,Amount Received,and amount Left for year … -
Mark as Read for a page in Django
I followed Sentdex Django tutorials to build a simple website. Now I want to add mark as read for each tutorial. If every tutorial is read then that particular series should be marked as read. Can you suggest how should I approach? class blogCategory(models.Model): blog_category = models.CharField(max_length=200) image = models.ImageField (upload_to ='static/images/models') category_summary = models.CharField(max_length=200) category_slug = models.CharField(max_length=200) class Meta: verbose_name_plural = "Categories" def __str__(self): return self.blog_category class blogSeries(models.Model): blog_series = models.CharField(max_length=200) image = models.ImageField (upload_to ='static/images/models') blog_category = models.ForeignKey(blogCategory, default=1, verbose_name = "Category", on_delete = models.SET_DEFAULT) series_summary = models.CharField(max_length=200) class Meta: verbose_name_plural = "Series" def __str__(self): return self.blog_series class blog(models.Model): completed=models.BooleanField(default=False) blog_title = models.CharField(max_length=200) image = models.ImageField (upload_to ='static/images/models',blank=True) blog_contents = models.TextField(default="") blog_publishedDate = models.DateTimeField("Date Published",default=datetime.now()) blog_series = models.ForeignKey(blogSeries, default=1, verbose_name="Series", on_delete=models.SET_DEFAULT) blog_slug = models.CharField(max_length=200, default=1) def __str__(self): return self.blog_title -
AJAX post request with django and python
I am trying to build a web app on django where a user can record something which then gets turned into text and after that sent to the server with AJAX. I did some research and found this article: https://medium.com/@manask322/implementing-speech-to-text-feature-in-a-django-app-f0fa53bb3e03 So I copied the html code: (this is only the part I copied) <div id='result'> Your text will appear here </div> <br> <div id= 'record'> <button onclick="startConverting()" class='btn btn-info btn-sm' id="re">record</button> <button class='btn btn-info btn-sm ml-3' value="Send" id="send">Send</button> </div> <script> function startConverting() { document.getElementById("re").style.visibility = "hidden"; var r=document.getElementById('result'); var spr=new webkitSpeechRecognition(); //Initialisation of web Kit spr.continuous=false; //True if continous conversion is needed, false to stop transalation when paused spr.interimResults=true; spr.lang='en-IN'; // Set Input language spr.start(); //Start Recording the voice var ftr=''; spr.onresult=function(event){ var interimTranscripts=''; for(var i=event.resultIndex;i<event.results.length;i++) { var transcript=event.results[i][0].transcript; transcript.replace("\n","<br>") if(event.results[i].isFinal){ ftr+=transcript; } else interimTranscripts+=transcript; } r.innerHTML=ftr +interimTranscripts ; }; spr.onerror=function(event){}; } $(document).ready(function() { $("#send").click(function(event){ $.ajax({ type:"POST", url:"/audio_data", data: { send : $('#result').html() }, }); }); }); </script> </div> But changed the function in views.py a bit: @csrf_exempt def audio_data(request): if request.method == 'POST': result = request.POST['send'] return render(request, 'success.html') elif request.method == 'GET': return render(request, 'afterContinue.html') The recording works and it also displays the text you say but when … -
Twisted , Channels is not installing - nor through pip neither through Manual Installation
I am building a Blog WebApp. Everything is working fine. BUT Twisted is not installing in cmd. -----------------------------------------The Problem---------------------------------------- My code consumers.py from channels.generic.websocket import AsyncJsonWebsocketConsumer When i import this in consumers.py an Error is raised in cmd while server was running. The Error was :- ModuleNotFoundError: No module named 'channels.generic' Then i searched this Error on Google then, I saw an Answer of this Question and The Answer was to pip install channels. Then i install it, AND while installing it , An main/Big Error is raised This Error. AND i now think this error is raising from Twisted, because channels and twisted are connected libraries This Error is raising again and again, whenever i try to install channels and Twisted. Before few hours ago i was trying to install Twisted through pip. BUT then error occurred and then i installed it manually from Here. I downloaded Twisted‑20.3.0‑cp38‑cp38‑win_amd64.whl. AND my python version is Python 3.8.2. When i open python Idle and enter import twisted to make sure that is is installed or not, Then no error is occuring ( It means that Twisted is installed , Why django-channels is not installing ). BUT twisted is not running in my … -
Redirect www to root (Django WSGI LetsEncrypt) is failing - Not Found
I’m having trouble understanding what’s missing where I’ve added a LetsEncrypt certificate to a Django web application hosted on Linode (CentOS 7) and using Apache. I used the certbot command to obtain an SSL certificate and noted the changes it added to the VirtualHosts files. certbot --apache I included with the root and www domains when prompted. Here’s what LetsEncrypt added to the /etc/httpd/sites-available directory. <server_name>.com.conf <VirtualHost *:80> # Default from LetsEncrypt RewriteEngine on RewriteCond %{SERVER_NAME} =www.<server_name>.com [OR] RewriteCond %{SERVER_NAME} =<server_name>.com RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent] </VirtualHost> And <server_name>.com-le-ssl.conf (where it wrapped it in mod_ssl and added the LE certificate lines) <IfModule mod_ssl.c> <VirtualHost *:443> # Load wsgi module LoadModule wsgi_module <details> # NOTE. When assigning a LetEncrypt certbot --apache the WSGI lines need to # be commented out. WSGIDaemonProcess <name> <details> WSGIProcessGroup <name> WSGIScriptAlias / <wsgi.py path> Alias /static <static_folder_path> <Directory <static_folder_path>> Require all granted </Directory> Alias /media <media_folder_path> <Directory <media_folder_path>> Require all granted </Directory> <Directory <Django_app_path>> <Files wsgi.py> Require all granted </Files> </Directory> ServerName <servername.com> Include /etc/letsencrypt/options-ssl-apache.conf ServerAlias www.<servername.com> SSLCertificateFile /etc/letsencrypt/live/<servername.com>/cert.pem SSLCertificateFile /etc/letsencrypt/live/<server_name>.com/cert.pem SSLCertificateKeyFile /etc/letsencrypt/live/<server_name>.com/privkey.pem SSLCertificateChainFile /etc/letsencrypt/live/<server_name>.com/chain.pem </VirtualHost> </IfModule> It also added an Include httpd.conf referencing the above. It may have added more. These were the changes I'm aware … -
activate python function with arguments using html in django
So, I'm trying to make a button where you can activate a python script using an HTML button, here's what I got. HTML <script> function login(){ $.ajax({ url: "/python_file", context: document.body }).done(function() { alert('finished python script');; }); } </script> <input id="clickMe" type="button" value="clickme" onclick="login();" /> urls.py urlpatterns = [ path('', views.home, name="index"), path('python_file', views.python_file), ] views.py from django.shortcuts import render def home(request): return render(request, "login/login.html") def python_file(email, password): pass but, how can I pass in an argument into the function? Any help is appreciated! -
How to filter form based on foreign key?
How can I filter fields in my TopForm in such a way that when a user selects a teacher, automatically all other fields show related values to the teacher. Suppose Adam is the teacher and in the Network department teaches network programming in the 4th semester(added in the admin). Now the user selects Adam, when Adam selected, the department dropdown shows only Network which is related to Adam and so on. forms.py class AnswerForm(ModelForm): class Meta: model = Student_Answer fields = ('answer',) labels = {'answer': ''} widgets = { 'answer': RadioSelect(choices=RATING_CHOICES)} class TopForm(forms.Form): teacher = forms.ModelChoiceField(queryset=Teacher.objects.all()) department = forms.ModelChoiceField(queryset=Department.objects.all()) subject = forms.ModelChoiceField(queryset=Subject.objects.all()) semester = forms.ModelChoiceField(queryset=Semester.objects.all()) models.py class Question(models.Model): question = models.CharField(max_length=200) class Department(models.Model): name = models.CharField(max_length=60) class Semester(models.Model): num = models.IntegerField(choices=SEMESTER, default=1) class Subject(models.Model): name = models.CharField(max_length=100) code = models.CharField(max_length=5, null=True) semester = models.ForeignKey(Semester, on_delete=models.CASCADE, null=True) department = models.ManyToManyField(Department) class Teacher(models.Model): name = models.CharField(max_length=200) last_name = models.CharField(max_length=200, null=True) department = models.ManyToManyField(Department) subject = models.ForeignKey(Subject, on_delete=models.CASCADE) class Student_Answer(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) teacher = models.ForeignKey(Teacher, on_delete=models.CASCADE) question = models.ForeignKey(Question, on_delete=models.CASCADE) subject = models.ForeignKey(Subject, on_delete=models.CASCADE) department = models.ForeignKey(Department, on_delete=models.CASCADE) semester = models.ForeignKey(Semester, on_delete=models.CASCADE) answer = models.SmallIntegerField(choices=RATING_CHOICES, default=None) -
Reversing in Django - Trying to Reverse from Update View to Detail View in Django
I am trying to reverse to the Detail View after the Update View and to List View after Delete View. How can I implement this. I am getting an error reverse not defined. Thanks #Contents of Models.py from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver # Create your models here. class Profile(models.Model): OPTIONS_PROFILE_TYPE = ( ('single', 'Single'), ('family', 'Family'), ) OPTIONS_LOCATIONS = ( ('USA', 'USA'), ('Canada', 'Canada'), ) user = models.OneToOneField(User, on_delete=models.CASCADE, help_text='User Name') display_name = models.CharField(null=True, max_length = 16, help_text='Optional Display Name' ) profile_type = models.CharField(null=True, choices=OPTIONS_PROFILE_TYPE, max_length=10) location = models.CharField(null=True, max_length = 30, choices=OPTIONS_LOCATIONS, help_text='Optional Location') biography = models.CharField(null=True, blank=True, max_length = 500, help_text='Optional Biography') # Metadata class Meta: ordering = ['profile_type'] # Methods def get_absolute_url(self): #Returns the url to access a particular instance of MyModelName. return reverse('profile-detail', args=[str(self.id)]) def __str__(self): #String for representing the MyModelName object (in Admin site etc.). return self.user.username #Contents of Views.py from datetime import datetime from django.shortcuts import render from django.urls import path from django.http import HttpRequest from .models import Profile from django.views.generic import FormView, CreateView, DetailView, UpdateView, DeleteView, ListView from django.shortcuts import redirect from django.urls import reverse class ProfileListView(ListView): model = Profile def get_context_data(self, …