Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Sending data from search bar to url
I need to send the raw text from a search bar input to my url, but I am getting query strings and I can't figure out how to convert it into text I can use This is the html that handles said bar <form method ='GET' action="/entry/"> <input class="search" type="text" placeholder="Search Encyclopedia"> </form> -
django channels emoji and images [closed]
I would like to send emojis and images in Django channels chat app, Is it possible to do with the integration of Django-ckedior, any help would be great, thanks! -
django template get key and value seperate to display
In django template i am getting the value like : {"A":"12","B":"13"} how can i display values in template through loop like : A - 12 B - 13 Can anyone have any idea please help me related this -
sqlite3.ProgrammingError: SQLite objects created in a thread can only be used in that same thread. In django 2.2
I'm facing this issue in test server. but not in production. I tried some of the solutions like python manage.py runserver --noreload and edit /lib/python3.6/site-packages/django/utils/autoreload.py this file. Mentioned in the document. https://github.com/django/django/commit/5bf2c87ece216b00a55a6ec0d6c824c9edabf188 This the error message look like, sqlite3.ProgrammingError: SQLite objects created in a thread can only be used in that same thread. The object was created in thread id 140000522213120 and this is thread id 140000744696768. Please suggest me a solution to rectify this problem, Anyone faced this issue before. Help me to solve this issue. -
django.urls.exceptions.NoReverseMatch:
I'm trying to create custom multiple user types registration and I keep running into this error: django.urls.exceptions.NoReverseMatch: Reverse for 'login' not found. 'login' is not a valid view function or pattern name. The main issue is I have not yet created any 'login' view function Here are my project urls `from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('users/', include('users.urls')), ]` and these are my app's urls from django.urls import path from . import views urlpatterns = [ path('register/',views.register,name='register'), path('customer_register/',views.customer_register.as_view(),name='customer_register'), path('business_register/',views.business_register.as_view(),name='business_register'), ] these are the relevant view functions from django.shortcuts import render from django.views.generic import CreateView from .forms import Customer_userRegisterForm,Business_userRegisterForm from .models import User,Business,Customer def register(request): return render(request,'users/register.html') class customer_register(CreateView): model = User form_class = Customer_userRegisterForm template_name = 'users/customer_register.html' class business_register(CreateView): model = User form_class = Business_userRegisterForm template_name = 'users/business_register.html' I have tried to look at solutions to similar questions but none works for me. please help me solve the problem. -
NodeJS or Django for machinelearning and API?
I am developing a project in which FrontEnd is Flutter app and I want to make a backend with machine learning and Mongo DB. I know Django and Nodejs both. I tried Django REST Framework but didnt like it at all as I am used to make APIs in NodeJS as my database is also MongoDB. I consider NodeJS to be good for making REST APIs and Python good for machine learning. Spawning child processes is not a great idea please suggest one language that can I use for my project backend. -
HTML barcode scanner to input field
I was just wondering if there is any way to have a barcode scanner input in my Django project. I want to be able to be able to scan a barcode from a mobile device and have the value of that code to occupy an input field where the user can then search. Any help is appreciated cheers -
Nodejs Templating
As in Django template inheritance, we can use base_template, right?. We can pass content to base_template and it returns with an updated template. Can we do the same in NODEJS? I know we can pass params and use that in individual templates. -
Toggle switch on and off from Django model using jquery
I have the below in my model.py from which I have the boolean value (tunnel_status): class IPSEC(models.Model): tunnel_name = models.CharField(max_length=100) tunnel_ip = models.CharField(max_length=100) tunnel_acl = models.CharField(max_length=100, default='acl') tunnel_acl_conf = models.CharField(max_length=1000, default='access-list 1') tunnel_status = models.BooleanField(default=False) I have the below in my HTML form (Have paste only the relevant code): {% for items in ipsec %} <tbody> <tr> <td>{{ items.tunnel_name }}</td> <td class="text-center">{{ items.tunnel_ip }}</td> <td class="identifyingClass"><a data-toggle="modal" data-target="#myModal{{ items.id }}" href="/ipsecacl/?acl={{ items.tunnel_acl }}">{{ items.tunnel_acl }}</a></td> <td> <label class="switch"> <div id="statvalue">{{ items.tunnel_status }}</div> <input type="checkbox" id="stats"> <span class="slider round"></span> </label> </td> </tr> {% endfor %} basically, I want to toggle the switch in the table base on the boolean values True = switch on and False = switch off. I know I have to use Jquery to accomplish this. But I lack a bit of knowledge on this. -
Django Form Field Not Setting Value After Submitting
I'm trying to post data from a form that contains incomplete data (I set the missing data in the View class before saving) for the following model. But the form does not get submitted as it is invalid (it's missing the harvest_amount, but I set the value on the webpage before submitting. class Harvest(models.Model): harvest_amount = models.IntegerField(validators=[MinValueValidator(limit_value=0)]) harvest_date = models.DateField() harvest_for_plant = models.ForeignKey(Plant, on_delete=models.CASCADE) and my form class HarvestCreationForm(forms.ModelForm): class Meta: model = Harvest fields = [ 'harvest_amount' ] def is_valid(self): //check if Id in the url contains a valid id for a plant return True -
Django how to get absolute urls in template?
I want to have on "courses.html" template 2 different objects, category and course so the urls for each category should look like "0.0.0.0:8000/category/python" but instead it is "0.0.0.0:8000/courses/python". Is there any way to have a proper absolute url from object? main views.py def courses(request): return render(request=request, template_name="main/courses.html", context={'courses': Course.objects.all, 'categories': Category.objects.all}, ) courses.html {% extends "main/header.html" %} {% block content %} {% for category in categories %} <a href="{{ category.slug }}"/> <p>{{ category }}</p> </a> {% endfor %} {% for course in courses %} <a href="{{ course.slug }}"/> <p>{{ course }}</p> </a> {% endfor %} -
Django - How do I order results by a SerializerMethodField field in a ViewSet?
I have a complicated logic to compute the custom field location in AdSerializer and a complicated logic to get the final queryset in AdViewSet. How can I order the final result by location before returning it? class AdSerializer(serializers.ModelSerializer): location = serializers.SerializerMethodField() def get_location: # logic to get a location of the ad class AdViewSet(viewsets.ReadOnlyModelViewSet): queryset = Ad.objects.filter(...) serializer_class = AdSerializer def get_queryset(self): # logic to compute the final result return queryset -
Django, Ajax populate search results via .js with model data
I am new at the JS world and need help using AJAX to populate search results from my models data. In essence, when a user types something in the search form, the data filters through asynchronously with 'title__istarts_with' providing the correct options. I'm having trouble with how to dynamically populate the data with the correct syntax on the search-results.js with the html setup. this is my home.html: <div class="app-table"> <div class="row"> {% for pilot in pilots %} <div class="col-lg-4"> {% if pilot.poster %} <img class="thumbnail" src="{{ pilot.poster.url }}"> {% endif %} <div class="box-element product"> <p>{{pilot.title}}</p> <p>Page Count: {{pilot.count}}</p> <p>Creator: {{ pilot.writer }}</p> {% if pilot.script %} <a href="{{ pilot.script.url }}" target="_blank">Read Me</a> {% endif %} </div> </div> {% endfor %} </div> </div> this my search_results.js: const sbody=document.querySelector(".search-body") ... if(data.length===0){ searchOutput.innerHTML = "Sorry, mate. Script hasn't been donated yet!"; }else{ data.forEach(item=>{ sbody.innerHTML += ' <div> <p>${pilot.title}</p> <p>${pilot.count}</p> <p>${pilot.writer}</p> </div>'; }) } ... I also don't know the right syntax to populate the img and url tags? -
How does Django ORM pass raw SQL queries through Psycopg2?
When using psycopg2 as the database connector specified in a DATABASES constant in settings.py, how do raw SQL queries get handled? When you use django.db.connection and cursor.execute(), does it use Django's classes to handle things, or psycopg2s? -
How Should I install Djnago on Ubuntu 20.04 LTS
I am tried to install Djnago on ubuntu 20.04 LTS version. First of all I used the below code for install Python and that is, sudo apt-get install python3 Python version is 3.8.2. Then I used two steps for install Django, 1st step: sudo apt update 2nd step: sudo apt install python3-pip Error is showed in 2nd step and that is, Media change: please insert the disc labeled 'Ubuntu 20.04.1 LTS _Focal Fossa_ - Release amd64 (20200731)' in the drive '/cdrom/' and press [Enter] When I press Enter. It continuously showed but don't solved my problems. Now What should I do,please help me for solving this problem. -
Using Django forms to render a large query of radio buttons in a more user friendly way
I am trying to find a way to effectively display time slots that users can select at time of application. Sometimes there will be quite a large number of slots. The issue is that I am currently using radio buttons, and a ModelChoiceField. I've attached an image below of what I have currently. I have a few ideas, and I am not sure if I need to dig into React or another front end framework to get this done. What I want is to display the radio buttons in a way thats not just an enormous list immediately, but rather a shorter list paired down into groups. I've thought about using CSS to hide some of the times. Perhaps having a checkbox for every hour that can display and hide the radio buttons within that hour (most slots are 5 minutes), but I get stuck trying to filter and render the form that way using a ModelChoiceField. I also am open to just using check boxes to have the user select a few generic ranges and use that to programmatically select a slot if thats what it is... I am not sure thats the best user experience though, so I … -
In Heroku, how to running gunicorn & import whitenoise?
2020-10-01T03:28:40.496699+00:00 heroku[web.1]: Starting process with command `gunicorn Nstory.wsgi --log-file -` 2020-10-01T03:28:43.803839+00:00 heroku[web.1]: State changed from starting to up 2020-10-01T03:28:43.367859+00:00 app[web.1]: [2020-10-01 03:28:43 +0000] [4] [INFO] Starting gunicorn 20.0.4 2020-10-01T03:28:43.368669+00:00 app[web.1]: [2020-10-01 03:28:43 +0000] [4] [INFO] Listening at: http://0.0.0.0:35650 (4) 2020-10-01T03:28:43.368936+00:00 app[web.1]: [2020-10-01 03:28:43 +0000] [4] [INFO] Using worker: sync 2020-10-01T03:28:43.374298+00:00 app[web.1]: [2020-10-01 03:28:43 +0000] [9] [INFO] Booting worker with pid: 9 2020-10-01T03:28:43.382660+00:00 app[web.1]: [2020-10-01 03:28:43 +0000] [10] [INFO] Booting worker with pid: 10 2020-10-01T03:28:44.338145+00:00 app[web.1]: [2020-10-01 12:28:44 +0900] [9] [ERROR] Exception in worker process 2020-10-01T03:28:44.338188+00:00 app[web.1]: Traceback (most recent call last): 2020-10-01T03:28:44.338190+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/arbiter.py", line 583, in spawn_worker 2020-10-01T03:28:44.338191+00:00 app[web.1]: worker.init_process() 2020-10-01T03:28:44.338191+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/workers/base.py", line 119, in init_process 2020-10-01T03:28:44.338192+00:00 app[web.1]: self.load_wsgi() 2020-10-01T03:28:44.338192+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/workers/base.py", line 144, in load_wsgi 2020-10-01T03:28:44.338192+00:00 app[web.1]: self.wsgi = self.app.wsgi() 2020-10-01T03:28:44.338193+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/app/base.py", line 67, in wsgi 2020-10-01T03:28:44.338193+00:00 app[web.1]: self.callable = self.load() 2020-10-01T03:28:44.338194+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/app/wsgiapp.py", line 49, in load 2020-10-01T03:28:44.338194+00:00 app[web.1]: return self.load_wsgiapp() 2020-10-01T03:28:44.338195+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/app/wsgiapp.py", line 39, in load_wsgiapp 2020-10-01T03:28:44.338195+00:00 app[web.1]: return util.import_app(self.app_uri) 2020-10-01T03:28:44.338195+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/util.py", line 358, in import_app 2020-10-01T03:28:44.338196+00:00 app[web.1]: mod = importlib.import_module(module) 2020-10-01T03:28:44.338196+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/importlib/__init__.py", line 127, in import_module 2020-10-01T03:28:44.338197+00:00 app[web.1]: return _bootstrap._gcd_import(name[level:], package, level) 2020-10-01T03:28:44.338198+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1014, in _gcd_import 2020-10-01T03:28:44.338198+00:00 … -
How to add pagination in search.html - django
how to create pagination in search.html ? i want show 4 posts per page what must I do now ? any help please and thanks this is my views.py : class SearchView(ListView): template_name = 'website_primary_html_pages/search.html' paginate_by = 20 count = 0 def get_context_data(self, *args, **kwargs): context = super().get_context_data(*args, **kwargs) context['count'] = self.count or 0 context['query'] = self.request.GET.get('q') return context def get_queryset(self): request = self.request query = request.GET.get('q', None) if query is not None: android_results = Android.objects.search(query) linux_results = Linux.objects.search(query) tech_results = Tech.objects.search(query) mobile_results = Mobile.objects.search(query) windows_results = Windows.objects.search(query) # combine querysets queryset_chain = chain( android_results, linux_results, tech_results, mobile_results, windows_results ) qs = sorted(queryset_chain, key=lambda instance: instance.pk, reverse=True) self.count = len(qs) # since qs is actually a list return qs return Android.objects.none() # just an empty queryset as default and here is my search.html : {% for object in object_list %} {% with object|class_name as klass %} {% if klass == 'Mobile' %} <div class="card-deck"> <div class="card mb-3" style="max-width: 800px;"> <div class="row no-gutters"> <div class="col-md-4"> <a href='Mobile/{{ object.slug }}'><img style="height:100%;width:100%;border-radius:6.5px;" src="{{ object.get_image }}" class="rounded float-right" alt="..."></a> </div> <div class="col-md-8"> <div class="card-body"> <a href='Mobile/{{ object.slug }}'> <h5 class="card-title" id="primary_site_pages_app_name_control"> <b>{{ object.name }}</b></h5></a> <p class="card-text" id="font_control_for_all_pages">{{ object.app_contect|truncatechars_html:153|safe}}</p> </div> <div class="card-footer"> <small class="text-muted" id="date_post_control">{{ … -
How can install Django on Ubuntu 20.04 LTS
I am beginners as ubuntu user. SO I need help to install Django. Already I used below command to install python, sudo apt-get install python3 Then the python version is Python 3.8.2 -
1046, 'No database selected' - unable to create programmatically the models (created with models.Model definition)
I am using multiple dbs and changing databases based on specific users/vendor permissions in Django. I am able to create dbs dynamically. But I am unable to create programmatically the models (created with models.Model definition) in the specific dynamically/programmatically created database in mysql. I am trying to use the create_model function in the schema editor but it fails. Here is the model i am trying to create and the code used to create the db and model. The model creation fails mentioning that database has not been selected. def create_model(self, new_database, model, create_database, conn): from django.db import connection, connections from django.db.utils import OperationalError from testmodel.models import Testmodel if connections[create_database.get("id")]: db_conn = connections[create_database.get("id")] try: # below cursor works c = db_conn.cursor() # create_model function is fetched print(db_conn.schema_editor().create_model) # below fails # db_conn.schema_editor().create_model(Testmodel) # below fails with db_conn.schema_editor() as schema_editor: schema_editor.create_model(Testmodel) return True return True except OperationalError as e: # (1046, 'No database selected') error print(e) connected = False return connected else: connected = True return connected return False when running this function, it gives an error saying the database has not been selected. (1046, 'No database selected') To avoid permissions issue for mysql user related errors, I tried with root user … -
Django queryset syntax using WHERE IN clause question
I could use assistance with a queryset call. Here are the models: class User(AbstractUser): pass class Post(models.Model): posterID = models.ForeignKey("User", on_delete=models.CASCADE, related_name="post") content = models.TextField(blank=False) timestamp =models.DateTimeField(auto_now_add=True) class Follow(models.Model): followerID = models.ForeignKey("User", on_delete=models.CASCADE, related_name="follower") followingID = models.ForeignKey("User", on_delete=models.CASCADE, related_name="follower_id") I am trying to select all Post with a posterID that are matching the followingID in Follow and are being followed (followerID) by the current user. I believe my SQL should be as such: SELECT * FROM Post WHERE Post.posterID IN ( SELECT followingID FROM Follow WHERE followerID = request.user.id ) I am guessing that I could start with something like: (assuming that currently request.user id == 1) f = Follow.objects.filter(followerID=1) p = Post.objects.filter(posterID__in= [-- something with f--] ) Any help would be appreciated. Thanks. -
Django: save() prohibited to prevent data loss due to unsaved related object
Why i get this exception even when I saved instance before assigning it as foreign key to another instance? "save() prohibited to prevent data loss due to unsaved related object " header_slip.save() form.cleaned_data['session_row'] = row_pk form.cleaned_data['brk_slip_id'] = header_slip form.save() my code here. Pls help me, thank -
How can i JSON URL use in function at flask?
My code here. I dealing with covid site and i want to retrieve data from a url but i am failing on this. I can't get the data. How can i this json url adaptive function. from flask import Flask, render_template, request import json import requests app = Flask(__name__) headers = {'content-type': 'application/json'} url = 'https://opendata.ecdc.europa.eu/covid19/casedistribution/json' filename = requests.post(url, data=json.dumps(dict(mynum=123)), headers=headers) print('response', response.text) @app.route('/', methods=['GET']) def index(): return(render_template('home.html')) @app.route("/" , methods=['POST']) def result(): country1 = request.form['country'] casesCountry1 = getCases(country1) dateLabels = getDates() return(render_template('home.html', country1=country1, casesCountry1=casesCountry1, dateLabels=dateLabels )) def getCases(country): with open(filename) as json_file: jsonData = json.load(json_file) caseList = [] for record in jsonData['records']: if record['countriesAndTerritories'] == country: caseList.append(int(record['cases'])) return(list(reversed(caseList))) if __name__ == '__main__': app.run(debug=False) -
Django processing form data without having to create form with Django
So I've coded an HTML page with all the inputs ready to go. I was going to use this on my python HTTP server but instead I am going to use Django because people have been telling me its much better for server handling. I played around with the forms.py on django but the problem is there you have to create the forms in forms.py and then it constructs the HTML for you. I already have the HTML ready so is there a way for me to just process the form data without having to rewrite my whole form again in forms.py? Thanks -
no result appear when i use search django
i want make search from my models ( multiple models ) but it don't work what's the prblem ? i am using slug so my pages like Android/some-url | Mobile/some-url etc. and the result is : just show results for : without data from models so how to fix it please any help here is my code : views.py : class SearchView(View): template_name = 'website_primary_html_pages/search.html' paginate_by = 2 count = 0 def get_context_data(self, *args, **kwargs): context = super().get_context_data(*args, **kwargs) context['count'] = self.count or 0 context['query'] = self.request.GET.get('q') return context def get_queryset(self): request = self.request query = request.GET.get('q', None) if query is not None: android_results = Android.objects.search(query) linux_results = Linux.objects.search(query) tech_results = Tech.objects.search(query) mobile_results = Mobile.objects.search(query) windows_results = Windows.objects.search(query) # combine querysets queryset_chain = chain( android_results, linux_results, tech_results, mobile_results, windows_results ) qs = sorted(queryset_chain, key=lambda instance: instance.pk, reverse=True) self.count = len(qs) # since qs is actually a list return qs return Post.objects.none() # just an empty queryset as default search.html : <h2 id="search_page_design">{{ count }} results for <b>{{ query }}</b>: </h2> {% for object in object_list %} {% with object|class_name as klass %} {% if klass == 'Android' %} <div class='row'> <div class='col-12'> Blog post: <a href='{{ object.get_absolute_url }}'>{{ object.name }}</a> …