Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to convert mysql query to django orm
I'm trying to execute this query, it's working fine in MySQL workbench, but It's not working in python shell. And I have to export that result in an Excel sheet. -
How to extract particular record from QuerySet using Django?
let say : I have 'views.py' def login(request): if request.method == 'POST': # here 'Employees' is the model class having some fields as : name, email, pass, mobile etc. emp = Employees.objects.filter(email=request.POST['email'], password=request.POST['password']) if emp: # Now here I'm getting confused how to get particular record like id, email, pass from emp var to store in session. I might be wrong cuz so please ignore my mistakes and give me best way to do that request.session['id'] = emp[0].id ... some code ... return redirect('/homepage') else: return render(request, 'forms/login.html') else: ... some code ... At the last I'm saying that this is only the hint what I want to get from queryset. Please don't ask why I'm doing that stuff. Only what I found problem so sharing with all Thanks -
Restrict Azure Application access to a specific folder in OneDrive
We have a requirement to upload to and read files from a single folder in onedrive for Business through a Django app. We are using Microsoft Graph API with application permission. While the Azure provides Files.ReadWrite.All permission, the application can also potentially access all files and folders, as provided in graph permissions reference: Allows the app to read all files in all site collections without a signed in user. (ref: https://docs.microsoft.com/en-us/graph/permissions-reference) Is there a way to use Graph API's Application Files.ReadWrite.All Permission while restricting the application's access to a single folder in OneDrive? Thanks for the help. -
How to Solve Django Error Message : TemplateDoesNotExist at
I am trying to do a project for a blog by django 3.1.2 , but unable to link the templates.I tried fixing it with **'DIRS': [os.path.join(BASE_DIR, 'templates'),]** I cannot find the logic miss. The template does exist and when I review the code, the query is performing correctly. I'm at a loss. my setting TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR,'templates'), ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] my blog images my blog urls.py from django.contrib import admin from django.urls import path,include urlpatterns = [ path('', include('posts.urls')), path('admin/', admin.site.urls), ] my posts urls.py from django.urls import path from . import views urlpatterns = [ path('', views.home, name='home'), ] my posts views.py from django.shortcuts import render from django.http import HttpResponse Create your views here. def home(request): return render(request,'posts/index.html') posts images -
Python Django project handling .env and SECRET_KEY on GitHub Actions + Kubernetes Deployment
We have a web service written in Django that is stored on GitHub. We used GitHub Actions to create a workflow that builds a Docker image and pushes it to Azure Container Registry. Then the workflow triggers a Terraform file that in turn provisions a Kubernetes Cluster and using a deployment.yaml it deploys the web service app on Kubernetes cluster. This whole process works fine but when pods are up they get terminated CrashLoopBackOff The terminated pod's log can be found in the ix output below http://ix.io/2BCx I know the log clearly shows that its missing some .env file and environment variables such as SECRET_KEY that seems to require these BEFORE the image build, we are unaware where and at what stage to provide these information to the image? Whether in the GH Actions workflow itself, in Dockerfile, a bash script to inject somewhere. Any guidance is highly appreciated. Thanks. -
Socket Communication between python and Django || HTTP - POST
I was trying to establish a communication between python and Django backend. I want to send an image from python using socket and HTTP post The Django View on successful post request will will save the image and respond back with an audio file . what I tried is client side # reading the file f = open(file_name, 'rb') file_content = f.read() f.close() # HTTP-POST Method req_data = '--{b}\r\n'.format(b=boundary) req_data += 'Content-Disposition: form-data; name="file"; filename={fn}\r\n'.format(fn=file_name) req_data += 'Content-Type: {ft}\r\n'.format(ft=file_type) req_data += '\r\n' req_data += '{file_content}\r\n'.format(file_content=file_content) req_data += '--{b}--'.format(b=boundary) # first method I tried req = 'POST /dataHandle/imagePort/ HTTP/1.1\r\n' req += 'Host: {host}\r\n'.format(host=host) req += 'Content-Type: image/jpeg; boundary={b}\r\n'.format(b=boundary) req += 'Content-Length: {l}\r\n'.format(l=len(req_data)) req += 'Connection: close\r\n' req += '\r\n' req += '{data}'.format(data=req_data) # second method I tried req = 'POST /dataHandle/imagePort/ HTTP/1.1\r\n' req += 'Host: {host}\r\n'.format(host=host) req += 'Content-Type: multipart/form-data; boundary={b}\r\n'.format(b=boundary) req += 'Content-Length: {l}\r\n'.format(l=len(req_data)) req += 'Connection: close\r\n' req += '\r\n' req += '{data}'.format(data=req_data) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((host, port)) byt = req.encode() data_len = s.send(byt) # Response Receive length = 1024 while True: f = open('response.mp3','wb') print ("Receiving...") l = s.recv(length) while (l): f.write(l) l = s.recv(length) f.close() print ("Done Receiving") s.send(' ') s.close() break print("outside") print("done") s.close() Django … -
How to hide pagination with Javascript
I am trying to hide my bootstrap pagination bar if the search results in less than one page of items. this is my home.html pagination: <div class="pagination" id="paginationField"> <nav aria-label="..."> <ul class="pagination", id="pagination"> <li class="page-item {% if not prev_page_url %}disabled {% endif %} "> <a class="page-link" href="{{ prev_page_url }}" tabindex="-1">Previous</a> </li> {% for n in page.paginator.page_range %} {% if page.number == n %} <li class="page-item active"> <a class="page-link" href="?page={{ n }}">{{ n }} <span class="sr-only">(current)</span></a> </li> {% elif n > page.number|add:-3 and n < page.number|add:3 %} <li class="page-item"> <a class="page-link" href="?page={{ n }}">{{ n }}</a> </li> {% endif %} {% endfor %} <li class="page-item {% if not next_page_url %}disabled {% endif %} "> <a class="page-link" href="{{ next_page_url }}">Next</a> </li> </ul> </nav> </div> Here is my js file: function showHidePagination() { if(document.getElementById('paginationField').length > 15) { document.getElementById('pagination').style.display='none'; } else { document.getElementById('pagination').style.display='block'; } } -
Receiving 'none' id value from post request input parameter in Django form
I am passing an id primary key in from a Django model called Project to projects.html where is says {{p.id}}. When I submit the form I get a 'none' value where it says print(id) even though the id is showing up properly in the browser. it's when I post the form it won't carry the value into the view. projects.html <form action="" method="POST">{% csrf_token %} <div class="form-group"> <input type="submit" value="View >>" class="btn btn-primary" /> <input type="hidden" id="{{p.id}}" class="btn btn-primary" /> <div class="submitting"></div> </div> </form> views.py def projects(request): if request.method == 'POST': id = request.POST.get('id') print(id) project=Project.objects.get(id=id) context = { 'p' : project, } return render(request, 'residential/project_info.html', context=context) p=Project.objects.all() context = { 'projects' : p, } return render(request, 'residential/projects.html', context=context) -
celery worker only imports tasks when not detached
I'm trying to get my django app to submit tasks to a celery worker and it's succeeding when the worker is run attached. As soon as I add the --detach the tasks are failing to be registered. [2020-10-26 04:09:33,159: ERROR/MainProcess] Received unregistered task of type 'devapp.tasks.create_random_files'. The message has been ignored and discarded. Did you remember to import the module containing this task? Or maybe you're using relative imports? Please see http://docs.celeryq.org/en/latest/internals/protocol.html for more information. The full contents of the message body was: '[[20, "blah", 5120], {}, {"callbacks": null, "errbacks": null, "chain": null, "chord": null}]' (93b) Traceback (most recent call last): File "/pysite/project/venv/lib/python3.6/site-packages/celery/worker/consumer/consumer.py", line 562, in on_task_received strategy = strategies[type_] KeyError: 'devapp.tasks.create_random_files' In my tasks.py I have import os import string import subprocess from celery import shared_task, task @shared_task(name='devapp.tasks.create_random_files') def create_random_files(total,filename,size): for i in range(int(total)): filenum = str(i).zfill(5) rnd_filename = '/brdis/{}-{}'.format(filenum,filename) with open(rnd_filename, 'wb') as f: f.write(os.urandom(size)) f.close return '{} random files created'.format(total) and in my views.py I have from django.shortcuts import render from django.http import HttpResponse from django.contrib import messages from django.views.generic import TemplateView from django.views.generic.list import ListView from django.views.generic.edit import FormView from django.shortcuts import redirect from .forms import CreateRandomFilesForm, GetFileListForm, ClamScanFileForm from .tasks import create_random_files, clamscanfile class ClamScanFileView(FormView): … -
Cannot resolve NoReverseMatch at / error in Django
I am trying to make an auction website (for a project). And we need to have an option to add each product to the "watchlist". However, I keep getting error when clicking on "watchlist" button. This is in Python using Django. This is the exact error I'm getting: NoReverseMatch at /viewlisting/3/addwatchlist Reverse for 'addwatchlist' with arguments '('',)' not found. 1 pattern(s) tried: ['viewlisting/(?P<listing_id>[0-9]+)/addwatchlist$'] Here is a summary of my code: urls.py: from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index"), path("login", views.login_view, name="login"), path("logout", views.logout_view, name="logout"), path("register", views.register, name="register"), path("create_listing", views.create_listing, name="create_listing"), path("viewlisting/<int:listing_id>", views.viewlisting, name="viewlisting"), path("viewlisting/<int:listing_id>/addwatchlist", views.addwatchlist, name="addwatchlist") ] views.py: def viewlisting(request,listing_id): productname= listings.objects.get(id=listing_id) name= productname.name description = productname.description image = productname.image price= productname.price seller = productname.seller category = productname.category date = productname.date productid= productname.id return render(request, "auctions/viewlisting.html",{ "name":name, "description":description, "image":image, "price":price, "seller":seller, "category":category, "date":date, "id":productid }) def addwatchlist(request,listing_id): if request.method == "POST": item_exists= watchlist.objects.filter( id = listing_id, user= request.user.username ) if item_exists: show_watchlist = watchlist.objects.all() exist_alert= "This item already exists in your watchlist!" return render(request,"auctions/viewlisting.html",{ "alert":exist_alert, "show_watchlist":show_watchlist }) else: new_item = watchlist() new_item.user = request.user.username new_item.listing = listings.objects.get(id=listing_id).name new_item.save() success_alert = "This item was added to your watchlist!" show_watchlist = watchlist.objects.all() return render(request,"auctions/viewlisting.html",{ "alert": … -
RelatedObjectDoesNotExist -- relationship error between models?
I am currently creating an application called "Hospital Management System," where patients can appoint doctors (through a system that I have not implemented yet). Currently, I am encountering an error regarding "RelatedObjectDoesNotExist." Here is the full error: Environment: Request Method: POST Request URL: http://127.0.0.1:8000/hms_app/doctor_register/ Django Version: 3.1.2 Python Version: 3.8.5 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'hms_app'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "C:\Users\acer\anaconda3\envs\myDjangoEnv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\acer\anaconda3\envs\myDjangoEnv\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\acer\Desktop\My_Django_Stuff\hospital_management_system\hms_app\views.py", line 60, in doctor_register doctor.doctor_profile.doctor_first_name = doctor_profile_form.cleaned_data.get('doctor_first_name') File "C:\Users\acer\anaconda3\envs\myDjangoEnv\lib\site-packages\django\db\models\fields\related_descriptors.py", line 421, in __get__ raise self.RelatedObjectDoesNotExist( Exception Type: RelatedObjectDoesNotExist at /hms_app/doctor_register/ Exception Value: User has no doctor_profile. This error appears every time I try to register a doctor, but this does not happen when I try to register a patient I am suspecting that this error has to do with my models and how each of them relate. Right now, I am trying to implement multiple roles using Django's user model -- specifically, the roles are doctor and patient. Here is what I have coded so far: models.py from django.contrib.auth.models import AbstractUser from django.db import models … -
Nginx in docker container not serving static files
I recently took over someone's project and I am supposed to deploy it to a new server. There is an Nginx server serving the static files of a Django app. I keep getting a 404-not-found error from Nginx. Here is the Nginx.conf file: server { listen 80; server_name localhost; return 301 https://$host$request_uri; } server { listen 443 ssl http2 default_server; listen [::]:443 ssl http2 default_server; server_name localhost; charset utf-8; client_max_body_size 150M; include /config/nginx/proxy-confs/*.subfolder.conf; include /config/nginx/ssl.conf; location /static { sendfile on; sendfile_max_chunk 25m; alias /static; } location /media/user { sendfile on; sendfile_max_chunk 50m; internal; alias /media/user; } location /admin/login { return 301 " /login"; } location /media/protected { if ($http_user_agent ~* (360Spider|80legs.com|Abonti|AcoonBot|Acunetix|adbeat_bot|AddThis.com|adidxbot|ADmantX|AhrefsBot|AngloINFO|Antelope|Applebot|BaiduSpider|BeetleBot|billigerbot|binlar|bitlybot|BlackWidow|BLP_bbot|BoardReader|Bolt\ 0|BOT\ for\ JCE|Bot\ mailto\:craftbot@yahoo\.com|casper|CazoodleBot|CCBot|checkprivacy|ChinaClaw|chromeframe|Clerkbot|Cliqzbot|clshttp|CommonCrawler|comodo|CPython|crawler4j|Crawlera|CRAZYWEBCRAWLER|Curious|Curl|Custo|CWS_proxy|Default\ Browser\ 0|diavol|DigExt|Digincore|DIIbot|discobot|DISCo|DoCoMo|DotBot|Download\ Demon|DTS.Agent|EasouSpider|eCatch|ecxi|EirGrabber|Elmer|EmailCollector|EmailSiphon|EmailWolf|Exabot|ExaleadCloudView|ExpertSearchSpider|ExpertSearch|Express\ WebPictures|ExtractorPro|extract|EyeNetIE|Ezooms|F2S|FastSeek|feedfinder|FeedlyBot|FHscan|finbot|Flamingo_SearchEngine|FlappyBot|FlashGet|flicky|Flipboard|g00g1e|Genieo|genieo|GetRight|GetWeb\!|GigablastOpenSource|GozaikBot|Go\!Zilla|Go\-Ahead\-Got\-It|GrabNet|grab|Grafula|GrapeshotCrawler|GTB5|GT\:\:WWW|Guzzle|harvest|heritrix|HMView|HomePageBot|HTTP\:\:Lite|HTTrack|HubSpot|ia_archiver|icarus6|IDBot|id\-search|IlseBot|Image\ Stripper|Image\ Sucker|Indigonet|Indy\ Library|integromedb|InterGET|InternetSeer\.com|Internet\ Ninja|IRLbot|ISC\ Systems\ iRc\ Search\ 2\.1|jakarta|Java|JetCar|JobdiggerSpider|JOC\ Web\ Spider|Jooblebot|kanagawa|KINGSpider|kmccrew|larbin|LeechFTP|libwww|Lingewoud|LinkChecker|linkdexbot|LinksCrawler|LinksManager\.com_bot|linkwalker|LinqiaRSSBot|LivelapBot|ltx71|LubbersBot|lwp\-trivial|Mail.RU_Bot|masscan|Mass\ Downloader|maverick|Maxthon$|Mediatoolkitbot|MegaIndex|MegaIndex|megaindex|MFC_Tear_Sample|Microsoft\ URL\ Control|microsoft\.url|MIDown\ tool|miner|Missigua\ Locator|Mister\ PiX|mj12bot|Mozilla.*Indy|Mozilla.*NEWT|MSFrontPage|msnbot|Navroad|NearSite|NetAnts|netEstate|NetSpider|NetZIP|Net\ Vampire|NextGenSearchBot|nutch|Octopus|Offline\ Explorer|Offline\ Navigator|OpenindexSpider|OpenWebSpider|OrangeBot|Owlin|PageGrabber|PagesInventory|panopta|panscient\.com|Papa\ Foto|pavuk|pcBrowser|PECL\:\:HTTP|PeoplePal|Photon|PHPCrawl|planetwork|PleaseCrawl|PNAMAIN.EXE|PodcastPartyBot|prijsbest|proximic|psbot|purebot|pycurl|QuerySeekerSpider|R6_CommentReader|R6_FeedFetcher|RealDownload|ReGet|Riddler|Rippers\ 0|rogerbot|RSSingBot|rv\:1.9.1|RyzeCrawler|SafeSearch|SBIder|Scrapy|Scrapy|Screaming|SeaMonkey$|search.goo.ne.jp|SearchmetricsBot|search_robot|SemrushBot|Semrush|SentiBot|SEOkicks|SeznamBot|ShowyouBot|SightupBot|SISTRIX|sitecheck\.internetseer\.com|siteexplorer.info|SiteSnagger|skygrid|Slackbot|Slurp|SmartDownload|Snoopy|Sogou|Sosospider|spaumbot|Steeler|sucker|SuperBot|Superfeedr|SuperHTTP|SurdotlyBot|Surfbot|tAkeOut|Teleport\ Pro|TinEye-bot|TinEye|Toata\ dragostea\ mea\ pentru\ diavola|Toplistbot|trendictionbot|TurnitinBot|turnit|Twitterbot|URI\:\:Fetch|urllib|Vagabondo|Vagabondo|vikspider|VoidEYE|VoilaBot|WBSearchBot|webalta|WebAuto|WebBandit|WebCollage|WebCopier|WebFetch|WebGo\ IS|WebLeacher|WebReaper|WebSauger|Website\ eXtractor|Website\ Quester|WebStripper|WebWhacker|WebZIP|Web\ Image\ Collector|Web\ Sucker|Wells\ Search\ II|WEP\ Search|WeSEE|Wget|Widow|WinInet|woobot|woopingbot|worldwebheritage.org|Wotbox|WPScan|WWWOFFLE|WWW\-Mechanize|Xaldon\ WebSpider|XoviBot|yacybot|Yahoo|YandexBot|Yandex|YisouSpider|zermelo|Zeus|zh-CN|ZmEu|ZumBot|ZyBorg) ) { return 410; } sendfile on; sendfile_max_chunk 50m; internal; alias /media/protected; } location /media { sendfile on; sendfile_max_chunk 25m; alias /media; } location /media/images/company { alias /media/images/company; } location / { proxy_pass http://web:8000; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; … -
How can I upload a file with JSON data to django rest api?
I am using angular as the front-end scope and Django Rest as the back-end. Now I am facing a situation where I want to create a Model. The structure of a model is really complex in nature, I could use some other simple way outs but using JSON and passing the files with that can really simplify the logic and also make process really efficient. I am have been trying a lot but none of the ways seem to work. Can some someone help me with a standard way or tell me even it is possible or not. This the structure of my Typescript which I want to upload. import { v4 as uuid4 } from 'uuid'; export interface CompleteReport{ title: string; description: string; author: string; article_upload_images: Array<uuid4>, presentation_upload_images: Array<uuid4>, report_article: ReportArticle, report_image: ReportImage, report_podcast: ReportPodcast, report_presentation: ReportPresentation, report_video: ReportVideo, } export interface ReportArticle{ file: File; body: string; } export interface ReportPodcast{ file: any; } export interface ReportVideo{ file: Array<File>; } export interface ReportImage{ file: File; body: string; } export interface ReportPresentation{ body: string; } export interface UploadImage{ file: File; } -
The ignore_bad_filters parameter of the build_filters function
I have a TaskTemplateResource like this: class TaskTemplateResource(GCloudModelResource): pipeline_template = fields.ForeignKey( PipelineTemplateResource, 'pipeline_template') class Meta: queryset = TaskTemplate.objects.filter(pipeline_template__isnull=False, is_deleted=False) resource_name = 'template' authorization = TaskTemplateAuthorization() always_return_data = True serializer = AppSerializer() filtering = { "id": ALL, "business": ALL_WITH_RELATIONS, "name": ALL, "category": ALL, "pipeline_template": ALL_WITH_RELATIONS, "subprocess_has_update": ALL, "has_subprocess": ['exact'] } def build_filters(self, filters=None, **kwargs): if filters is None: filters = {} orm_filters = super(TaskTemplateResource, self).build_filters(filters, **kwargs) Super class GCloudModelResource: class GCloudModelResource(ModelResource): def build_filters(self, filters=None, ignore_bad_filters=False): if filters is None: filters = {} print filters orm_filters = super(GCloudModelResource, self).build_filters( filters, ignore_bad_filters ) print orm_filters class PipelineTemplateResource: class PipelineTemplateResource(GCloudModelResource): class Meta: filtering = { 'subprocess_has_update': ALL, 'has_subprocess': ['exact'] } The question is filter like this: <QueryDict: {u'has_subprocess': [u'true']}> but orm_filters like this: {'pipeline_template__exact': True} Why?The has_subprocess is a filed of PipelineTemplateResource. When the filter is: <QueryDict: {u'pipeline_template__has_subprocess': [u'true']}> the orm_filters will be: {'pipeline_template__has_subprocess__exact': True} -
DRF API not linking foreign key via signal
I have a model which has a post_save signal that creates another "default" model when it is created. This "default" model is linked via a foreign key, like so: @receiver(post_save, sender=Theme) def create_default_style(sender, instance, *args, **kwargs): if not instance.styles.exists(): style = Style(theme=instance) style.save() This signal works totally fine when the "Theme" model is created in a dev environment. However, when I try to save the "Theme" model via DRFs API, the "Style" model is linked (as per above code), then somehow the FK relationship is removed. I can't for the life of me figure out what is happening, except that it has something to do with the use of a PrimaryKeyRelatedField in the "Theme" serializer, as follows: class ThemeSerializer(serializers.ModelSerializer): styles = serializers.PrimaryKeyRelatedField(queryset=Styles.objects.all(), many=True, allow_null=True, required=False) If I change the PKRelatedField to a SerializerMethodField, the signal works correctly from both the app and DRF's API. While the workaround (SerializerMethodField) is fine, I am still interested to find out what is causing the problem with the PKRelatedField. -
Three.js and Django?
somebody knows if can i upload a Three.js project to Django? i did a project to upload jpg and png images in Django, but i have another project in three.js to use .OBJ images, but now i neet to include my Three.js project to my Django project but i don't know how and if its posible to do it... Thank u so much! enter image description here files to Django project files to Three.js project -
Django Localization: How to prevent translator from adding CSS or template filters?
For example: Lorem Ipsum <a href="%(ipsum_url)s"><u>Something something</u></a>. Would be an item in django-rosetta. The translator could do something like: Lorem Ipsum <a style="color: red;" href="%(ipsum_url)s"><u>Something something</u></a>. and it would change the styling found on the site. I am also not sure if more malicious things could be done with this. -
django-configurations can't find my configuration when using uwsgi
I'm trying to migrate a Django==2.1 project from one AWS instance to another. I did not create the project so I'm not sure exactly all the steps that they followed for deployment. I see that uWSGI==2.0.19.1 is in the requirements.txt file, so I'm trying to use that to run the project at port 8000. The project also uses the library django-configurations==2.1 to manage multiple configurations. They are in a folder called config with this structure. project/ config/ __init__.py common.py development.py local.py production.py staging.py manage.py wsgi.py ... The __init__.py file inside the config folder contains the following: from __future__ import absolute_import from .local import Local from .staging import Staging from .production import Production from .development import Development I'm trying to run the following command: uwsgi --http :8000 --module wsgi:application --chdir=/path/to/project And I'm getting this error: Traceback (most recent call last): File "./wsgi.py", line 16, in <module> from configurations.wsgi import get_wsgi_application File "/path/to/project/.env/lib/python3.6/site-packages/configurations/wsgi.py", line 14, in <module> application = get_wsgi_application() File "/path/to/project/.env/lib/python3.6/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application django.setup(set_prefix=False) File "/path/to/project/.env/lib/python3.6/site-packages/django/__init__.py", line 19, in setup configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) File "/path/to/project/.env/lib/python3.6/site-packages/django/conf/__init__.py", line 57, in __getattr__ self._setup(name) File "/path/to/project/.env/lib/python3.6/site-packages/django/conf/__init__.py", line 44, in _setup self._wrapped = Settings(settings_module) File "/path/to/project/.env/lib/python3.6/site-packages/django/conf/__init__.py", line 107, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/path/to/project/.env/lib/python3.6/importlib/__init__.py", … -
Datatable next page not accepting array
I sent some values to the django backend using ajax. I am now trying to pass result as array on ajax success which is working fine on datatable first page. But next page only reads the first value of the array. I have been been working on this for past weeks now. Any help will be appreciated. See my javascript code below on ajax success; var str = ""+response['counting']+""; var myarray = str.split(','); for(var i = 0; i < myarray.length; i++) { alert(myarray[i]); } Datatable next page couldn't read all array content say array is [3,5,11,13]. -
The Black Formatter - Python
I just started using the Black Formatter module with VSCode everything was going well till I just noticed that it uses double quotes over single quotes which I already was using in my code.. and it overrode that.. So, is there an Black Argument that I could add to VSCode which solves this problem? Thanks. -
Plotting multiple JSON subobjects in Chart.js Line chart ( with Time as x-axis)
I'm trying to plot data from multiple channels in Django. My JSON file looks like this: { "Channel1":[ { "Value":123, "Timestamp": someUnixTime }, { "Value":456, "Timestamp": someUnixTime }, { "Value":789, "Timestamp": someUnixTime } ], "Channel2":[ { "Value":312, "Timestamp": someUnixTime }, { "Value":654, "Timestamp": someUnixTime }, { "Value":987, "Timestamp": someUnixTime } ] } How can I plot a line for each channel? P.S. My actual dataset has somewhat around 73 channels and +100k entries. -
ForeignKey is not working django, I am using custom user model and I try both MySQL and PostgreSQL
in my SubUser model ForeignKey is not working when I add some sub user it does not get main user id to its user_id field. I try all solutions from stack overflow and I try this in both MySQL and PostgreSQL, here my codes: dashboard/model.py from django.db import models from django.conf import settings from django.contrib.auth.models import BaseUserManager from account.models import Account from django.contrib.auth import get_user_model # Create your models here. class CustomUserAdmin(BaseUserManager): ordering = ('email',) class SubUser(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, on_delete=models.CASCADE) image = models.ImageField(null=True, blank=True) email = models.EmailField(verbose_name="email", max_length=60, unique=True) fullname = models.CharField(max_length=220) phone_number = models.CharField(max_length=100, unique=True) address = models.CharField(max_length=220) user_role = models.CharField(max_length=220) def __str__(self): return self.fullname dashboard/views.py from django.shortcuts import render from django.contrib.auth.decorators import login_required from . import forms from django.conf import settings # Create your views here. @login_required(login_url='account:index') def dashboard(request): return render(request, 'dashboard/table.html') @login_required(login_url='account:index') def add_sub_user(request): form = forms.AddSubUserForm(request.POST) if form.is_valid(): obj = form.save(commit=False) obj.save() print(settings.AUTH_USER_MODEL) context = {'form':form} return render(request, 'dashboard/add_subuser.html',context) account/modules.py class Account(AbstractBaseUser): email = models.EmailField(verbose_name="email", max_length=220, unique=True) fullname = models.CharField(max_length=220) phone_number = models.CharField(max_length=220, unique=True) address = models.CharField(max_length=220) date_joined = models.DateTimeField(verbose_name='data joined', auto_now_add=True) last_login = models.DateTimeField(verbose_name='last login', auto_now_add=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) username = models.CharField(max_length=220, unique=True, blank=True) … -
adding initial value to Django model form
I just want to add an initial value to one field when it gets populated, this is my view def add_program(request): module = Module.objects.all() last_item = Programme.objects.filter(module_id__in=module).last() if last_item: day = last_item.day + 1 else: day = 1 initial_data = { 'day': day } if request.method == 'POST': form = ProgramAddForm(request.POST or None, request.FILES or None, initial=initial_data) if form.is_valid(): instance = form.save(commit=False) instance.save() return redirect('program_add') else: form = ProgramAddForm() return render(request, 'client_apps/program/form.html', {'form': form}) and form class ProgramAddForm(forms.ModelForm): class Meta: model = Programme fields = ['module', 'day', .........] even though initial value is passed nothing is visible in day field when form populates, is there any alternative method? -
DJANGO EMAIL CONFIRMATION: [WinError 10061] No connection could be made because the target machine actively refused it
I'm trying to send an email verification code for account confirmation. Now, the thing is that I am trying to send an email to myself first, and my other email. I have turned off my antivirus, so that shouldn't be a problem. Other than this I can't figure our what I did wrong that it is not sending emails on the gmail account. Please point out what I'm doing wrong. I even applied all the fixes mentioned by this thread. views.py from django.core.mail import send_mail from django.shortcuts import render,redirect from django.contrib import messages,auth from django.contrib.auth.models import User # this table already exists in django we import it from django.contrib.auth import authenticate, login from django.conf import settings from django.core.mail import EmailMessage def register(request): if request.method=='POST': fname = request.POST['fname'] lname=request.POST['lname'] #request.post[id of the input field] email = request.POST['email'] password = request.POST['pass'] password2 = request.POST['confirmpass'] agree=request.POST.get('agree') if fname == '': messages.warning(request, 'Please enter First name!') return redirect('register') if lname == '': messages.warning(request, 'Please enter Last name!') return redirect('register') if email == '': messages.warning(request, 'Please enter Email!') return redirect('register') if password == '': messages.warning(request, 'Please enter Password!') return redirect('register') if password2 == '': messages.warning(request, 'Please enter Confirm Password!') return redirect('register') if ('agree' not in … -
Django and Bootstrap Modal
Please help me to progress with my project. I'm new to Django and bootstrap and i'm currently working on a project. For the Registration of the user i'm using a modal. I've set up the following: The modal: <!-- Login/Register Starts --> <!-- Modal --> <div class="sign_up_modal modal fade" tabindex="-1" role="dialog" aria-hidden="true" id=bd-example-modal-lg> <div class="modal-dialog modal-lg" role="document"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button> </div> <div class="modal-body container pb20"> <div class="row"> <div class="col-lg-12"> <ul class="sign_up_tab nav nav-tabs" id="myTab" role="tablist"> <li class="nav-item"> <a class="nav-link active" id="home-tab" data-toggle="tab" href="#home" role="tab" aria-controls="home" aria-selected="true">Login</a> </li> <li class="nav-item"> <a class="nav-link" id="profile-tab" data-toggle="tab" href="#profile" role="tab" aria-controls="profile" aria-selected="false">Register</a> </li> </ul> </div> </div> <!-- Register Modal Starts --> <div class="row mt25 tab-pane fade" id="profile" role="tabpanel" aria-labelledby="profile-tab"> <div class="col-lg-6 col-xl-6"> <div class="regstr_thumb"> <img class="img-fluid w100" src="{% static 'images/resource/regstr.jpg' %}" alt="regstr.jpg"> </div> </div> <div class="col-lg-6 col-xl-6"> <div class="sign_up_form"> <form action="{% url 'register' %}" method="POST" id="register-form"> {% csrf_token %} {{form.as_p}} <div class="heading"> <h4>Register</h4> </div> <div class="row"> <div class="col-lg-12"> <button type="submit" class="btn btn-block btn-fb"><i class="fa fa-facebook float-left mt5"></i> Login with Facebook</button> </div> <div class="col-lg-12"> <button type="submit" class="btn btn-block btn-googl"><i class="fa fa-google float-left mt5"></i> Login with Google</button> </div> </div> <hr> <div class="form-group ui_kit_select_search mb0"> <select class="selectpicker" data-live-search="true" data-width="100%"> <option data-tokens="SelectRole">Landlord</option> …