Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django StreamingHttpResponse picamera runs but does not render the stream, please advise
I hope I find you well. I am really struggling with a personal project and would be really grateful if someone could please set me straight. I wish to stream video from a picamera in django. I saw some cv2 implementations, had some trouble with cv2 and decided to try an alternate route. Some of the code here is lifted from the picamera documentation and some is from some of the cv2 implementations I've come across. When I hit the django url, the camera begins to stream however the webpage is grey with a small box at the centre with no visible stream. Full code posted below. This is what I see Is anyone able to point me in the right direction? Thank you, Darren from django.shortcuts import render from django.http import HttpResponse from django.http import StreamingHttpResponse from doron.models import Storage from django.views import generic import picamera import io from threading import Condition from time import sleep class StreamingOutput(object): def __init__(self): self.frame = None self.buffer = io.BytesIO() self.condition = Condition() def write(self, buf): if buf.startswith(b'\xff\xd8'): # New frame, copy the existing buffer's content and notify all # clients it's available self.buffer.truncate() with self.condition: self.frame = self.buffer.getvalue() self.condition.notify_all() self.buffer.seek(0) return self.buffer.write(buf) … -
Is there a shorter / simpler query than this one?
I have this very simple models: a Clip can have many AdBase and an AdBase can have many Clip's. class AdBase(models.Model): title = models.CharField(max_length=200, default=None, null=True, blank=False) class Clip(models.Model): ads = models.ManyToManyField(AdBase, related_name='clips', through='ClipAd') class ClipAd(models.Model): clip = models.ForeignKey(Clip, on_delete=models.CASCADE, blank=False, null=False) ad = models.ForeignKey(AdBase, on_delete=models.CASCADE, blank=False, null=False) position = models.IntegerField(default=0, blank=False, null=False) I want in the class Clip, a query which returns all its clips ordered by their position. I've come up with this: class Clip(models.Model): ads = models.ManyToManyField(AdBase, related_name='clips', through='ClipAd') def ads_by_position(self): # there might be a simpler query than this: return [a.ad for a in ClipAd.objects.filter(clip=self).order_by('position')] But I'm sure there's a simpler syntax using the ads property of my class Clip but I didn't find one. Any idea (or is this the only solution)? -
when i run the app i am getting this error ModuleNotFoundError: No module named 'preferences' in django
when i tried to run the app in django, i am getting this error ModuleNotFoundError: No module named 'preferences', i have already installed pip install django-dynamic-preferences, can anyone please help me how to resolve this issue ? here i have shown my whole error log [2020-05-24 09:16:39 +0000] [13070] [INFO] Starting gunicorn 20.0.4 [2020-05-24 09:16:39 +0000] [13070] [INFO] Listening at: http://0.0.0.0:8000 (13070) [2020-05-24 09:16:39 +0000] [13070] [INFO] Using worker: sync [2020-05-24 09:16:39 +0000] [13073] [INFO] Booting worker with pid: 13073 [2020-05-24 09:16:40 +0000] [13073] [ERROR] Exception in worker process Traceback (most recent call last): File "/home/ubuntu/env/lib/python3.6/site-packages/gunicorn/arbiter.py", line 583, in spawn_worker worker.init_process() File "/home/ubuntu/env/lib/python3.6/site-packages/gunicorn/workers/base.py", line 119, in init_process self.load_wsgi() File "/home/ubuntu/env/lib/python3.6/site-packages/gunicorn/workers/base.py", line 144, in load_wsgi self.wsgi = self.app.wsgi() File "/home/ubuntu/env/lib/python3.6/site-packages/gunicorn/app/base.py", line 67, in wsgi self.callable = self.load() File "/home/ubuntu/env/lib/python3.6/site-packages/gunicorn/app/wsgiapp.py", line 49, in load return self.load_wsgiapp() File "/home/ubuntu/env/lib/python3.6/site-packages/gunicorn/app/wsgiapp.py", line 39, in load_wsgiapp return util.import_app(self.app_uri) File "/home/ubuntu/env/lib/python3.6/site-packages/gunicorn/util.py", line 358, in import_app mod = importlib.import_module(module) File "/usr/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line … -
Upload file django admin
i'm creating a admin form where users can upload files. I want this to be stored im a secure place where the public can't get it. I'm using a standard form with a filefield and no model. Is there a way i can store the files in a folder within the app folder? Thanks -
Django Admin redirect to ChangeList with filters
I have a House model and a Reserve model. There is an admin action for Reserve models that searches for optimal House models instances from the selected model. for example, this is the action method result: results = models.House.objects.filter(price__range = [queryset[0].price_from, queryset[0].price_to] ) I want the action method to redirect to House ChangeList and only show the objects in the returned result. -
Html how to inlcude script in my template?
I have a question for you. I'm trying to create a file js which contains all my chart in my html pages. The structure are the following: ___base.html ___scripts.html ___conto_economico.html ___charts.html In my base.html I have included the scripts.html in the following manner: {% block javascript %} {% include 'adminlte/lib/_scripts.html' %} {% endblock %} In my scripts.html I have included all scripts, also the charts.js file {% load static %} {% block scripts %} <script src="{% static 'admin-lte/plugins/jquery/jquery.min.js' %}"></script> <script src="{% static 'admin-lte/plugins/jquery-ui/jquery-ui.min.js' %}"></script> <script src="{% static 'admin-lte/plugins/chart.js/Chart.min.js' %}"></script> <script src="{% static 'charts/charts.js' %}"></script> {% endblock %} Finally, in conto_economico.html I have extends my base and include the scripts.html in the following manner: {% extends 'adminlte/base.html' %} {% load static %} {% block content %} {% include 'adminlte/lib/_scripts.html' %} ..... <canvas class=" w-100 " id="chart" height="180" ></canvas> ...... {% endblock content %} But my "chart" does not uploaded in my page. Where is the error? -
How to handle scroll function for the screen of different width including mobile width
i have asked question previously since nobody answer i am posting once again.How to handle the scroll function for different media width.So far i have used for cases for each screen width and loop the scroll function inside it.Every thing goes well except mobile size the thing is position of "#imagg" "#pid" ".logo-maker" and ".seperator" changes while scrolling in mobile screen (only when scrolling up and down). It executes the scrolling function of width 1230 instead of executing width of 767 px. Thank you for the solution. here if js file var screensize = window.innerWidth; $(document).ready(function(){ $(".menu-icon").on("click", function(){ $(".showhas").toggleClass("showing"); }); }); if(screensize<767 ){ window.onscroll=function(){ mobilefunction() }; } else{ window.onscroll = function() { myFunction() }; } function myFunction() { var scroll=document.getElementById("ws-scroll"); var imge= document.getElementById("imagg"); var para= document.getElementById("pid"); var sep = document.getElementById("sep"); var logomaker = document.getElementById("logohas") ; var heading= document.getElementById("sochead"); var cont = document.getElementById("contain1"); var logo = document.getElementById("logo") if ( screensize > 1230) { console.log(screensize); if (document.body.scrollTop > 90 || document.documentElement.scrollTop > 90) { imge.style.height = "78px"; imge.style.width= "89px"; imge.style.marginTop="27px"; imge.style.marginLeft="8px"; sep.style.height="96px"; sep.style.marginLeft="99px"; sep.style.marginTop="1px"; logomaker.style.marginTop="-105px"; logomaker.style.fontSize = "71px"; logomaker.style.marginLeft="92px"; para.style.marginTop= "-31px"; para.style.marginLeft="97px"; para.style.fontSize="9px"; heading.style.marginTop= "-33px"; cont.style.marginTop="68px"; } else { imge.style.height = "168px"; imge.style.width= "169px"; imge.style.marginTop="17px"; imge.style.marginLeft="0px"; sep.style.height="163px"; sep.style.marginLeft="182px"; sep.style.marginTop="4px"; logomaker.style.marginTop="-178px"; logomaker.style.fontSize = … -
IndexedDataItem in Python (Django)
I'm wondering if anyone could explain what an IndexedDataItem in Python using Django/Postgres is? django.db.utils.ProgrammingError: can't adapt type 'IndexedDataItem' Thanks in advance. -
django object is not getting created after posting data through form
I am practicing django by making a simple app. so, i am facing a problem in assigning a object to a variable(sorry i dont know how to write this word). First i took values in html form then passed it to a view where i am assigning all those values to a object variable of a model. The code is like this:- View.py from django.shortcuts import render from .models import Customer,Order from pizza.models import item def order(request): customer = Customer.objects.all() items=item.objects.all() context={'customer':customer,'items':items} return render(request,'pizza/order.html',context) def profile(request): if request.method=='POST': cusname_=request.POST['cusname'] cusphone_=request.POST['cusphone'] cusaddress_=request.POST['cusaddress'] cus=Customer.objects.get_or_create(cus_name=cusname_,cus_phone=cusphone_,cus_address=cusaddress_) item_list=request.POST.getlist('check') context={'entry':entry} return render(request, 'pizza/profile.html', context) Html:- <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>order time</h1> <form method="post" action=" {% url "profile" %}"> {% csrf_token %} <label for="name">Customer Name</label> <input type="text" name="cusname" id="name" placeholder="enter name"> <label for="phone">phone</label> <input type="text" name="cusphone" id="phone" placeholder="enter phone"> <label for="address">address</label> <input type="text" name="cusaddress" id="address" placeholder="enter address"><br> {% for item in items %} <input type="checkbox" name="check" id="item{{ item.id }}" value="{{ item.item_name }}"> <label for="item{{ item.id }}">{{ item.item_name }}={{ item.item_price }}</label> {% endfor %} <input type="submit" placeholder="submit"> </form> </body> </html> As you can see i am declaring a object variable "cus" in profile view but it is not getting declared.As if i … -
How to get limited amount of recent posts in django
I am a DJANGO beginner and I am making a biography app as my first project. I want my homepage to show a limited number of recent posts. I am providing my Django files so you'll look up and help me with this problem. Thanks #views.py from django.views.generic import TemplateView, ListView, DetailView from .models import About # Create your views here. class Home(ListView): """docstring for Home""" template_name = 'home.html' model = About recents = About.objects.all() for recent in recents: if recent.was_published_recently(): print (recent.id) class BiographyDetail(DetailView): """docstring for BiographyDetail""" model = About template_name = 'details.html' class About(TemplateView): """docstring for BiographyDetail""" template_name = 'about.html' model = About class Contacts(TemplateView): """docstring for BiographyDetail""" template_name = 'contact.html' model = About class Projects(TemplateView): """docstring for BiographyDetail""" template_name = 'projects.html' model = About class Search(TemplateView): """docstring for BiographyDetail""" template_name = 'search.html' model = About #models.py I have defined a function was_published_recently which tells whether any posts was published in that certain interval as you can figure that out by its name from django.db import models from django.utils import timezone import datetime # Create your models here. TYPE = ( ('politician','POLITICIAN'), ('poet','POET'), ('author','AUTHOR'), ('actor','ACTOR'), ) class About(models.Model): name = models.CharField(max_length = 200, default='') quote = models.CharField(max_length = … -
Using telethon with django: There is no current event loop in thread 'Thread-1'
I want to use Telethon from the django. But when I am running it, I am getting following error: RuntimeError: There is no current event loop in thread 'Thread-1'. my code views.py: from django.shortcuts import render,HttpResponse from telethon.sync import TelegramClient, events async def join(client): ch = '@andeh_ir' try: await client(JoinChannelRequest(ch)) print('[+] Joined The Channel') except: print('[-] skiped') def addChannel(request): api_id = XXXXXX api_hash = 'xxxxxxxxxxxxxxxxxxxxx' client = TelegramClient('+254716550762', api_id, api_hash ) with client: client.loop.run_until_complete(join(client)) return HttpResponse('addChannel') -
Can't add a new page via django-cms because it can't find template
I am trying to integrate djangocms-blog into an existing project of mine which seems to be quiet challenging. Since djangocms-blog expects a set up and running django-cms project (which doesn't suit my needs since I have an already running own project..), I created one from scratch to copy/paste the necessary parts to my existing project (like settings and templates especially). Now I would like to add a blog-app to my existing project using djangocms-blog. Therefor I first of all need to add a new django-cms page which doesn't work. It always throws the below shown error: Settings.py [...] INSTALLED_APPS = [ # Django 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', # My Apps 'calculator', 'accounts', 'feeder', # Data 'nomnom', # Blog App Stuff 'blog', 'menus', 'cms', 'cms.utils', 'treebeard', 'filer', 'easy_thumbnails', 'aldryn_apphooks_config', 'parler', 'taggit', 'taggit_autosuggest', 'meta', 'sortedm2m', 'djangocms_admin_style', 'djangocms_blog', 'djangocms_file', 'djangocms_icon', 'djangocms_link', 'djangocms_picture', 'djangocms_style', 'djangocms_snippet', 'djangocms_googlemap', 'djangocms_video', ] SITE_ID = 1 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', 'cms.middleware.user.CurrentUserMiddleware', 'cms.middleware.page.CurrentPageMiddleware', 'cms.middleware.toolbar.ToolbarMiddleware', 'cms.middleware.language.LanguageCookieMiddleware' ] ROOT_URLCONF = 'CFD.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(BASE_DIR, 'templates'), os.path.join(BASE_DIR, 'accounts/templates/accounts'), os.path.join(BASE_DIR, 'blog/templates/blog'), os.path.join(BASE_DIR, 'blog', 'templates'), ], 'APP_DIRS': False, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'django.template.context_processors.media', 'django.template.context_processors.csrf', 'django.template.context_processors.tz', 'sekizai.context_processors.sekizai', … -
How to link to a particular post id
i am working on a project in Django and i am having issues on how i can link to a particular post id. I have list of posts on homepage and also an ellipsis on top of each post, when ellipsis is clicked it popup a modal. In the modal i have a link 'edit post' that takes me to update_post.html, but when i click on the second post ellipsis and modal popup, then i click on the 'edit post' link it takes me to update_post.html but only takes the latest post id in url instead of the second post id in url. For example: it takes me to (first post): http://127.0.0.1:8000/update/status/11/ instead of (second post): http://127.0.0.1:8000/update/status/17/ home.html {% if all_images %} {% for post in all_images %} <ul> <li class="ellipsis float-right"> {% include 'newfeeds_modal.html' %} </li> </ul> {% endfor %} {% endif %} newfeeds_modal.html <!-- User Ellipsis --> {% if post.poster_profile == request.user %} <a data-toggle="modal" data-target="#homeuserellipsisModal" class="font-small float-right"> <img src="{{ '/static/' }}images/more_icon.png" width="16" height="16" alt="more" class="float-right" style="position:relative;top:13px;left:10px;"> </a> <!-- Home User Ellipsis Modal --> <div class="modal fade animated fadeIn" id="homeuserellipsisModal" role="dialog"> <div class="modal-dialog modal-dialog-centered" role="document"> <div class="modal-content w-75 mx-auto"> <div class="card text-center w-100" id="following-modal"> <ul class="list-group list-group-flush"> <li … -
Need help understand the behavior of URLs for a django website
I am coding a website for practice which has the following functionality 1) Display employee data (localhost:8000/payroll) 2) Add Employee (localhost:8000/addemployee) 3) Edit Employee (localhost:8000/editemployee) 4) Download report (localhost:8000/downloadreport) Below screenshots indicate the operations as they happen. homepage delete employee Code for my deleteemployee view is as follows where if the delete succeeds I use render to take the user back to my home page(at least I think that is how it should work). But if you notice the URL never changes to index i.e localhost:8000/payroll even though the homepage is displayed the delete employee URL is still showing. What am I doing wrong here ? EXPECTED URL AFTER CLICKING REMOVE IS BELOW http://127.0.0.1:8000/payroll/ ACTUAL URL AFTER CLICKING REMOVE IS BELOW http://127.0.0.1:8000/payroll/deleteemployee?employee_id=32 Python Version -- 3.7 Django Version -- 3.0 try: e = Employee.objects.get(employee_id = request.GET.get('employee_id')) e.delete() employee_list = Payroll.objects.select_related('employee_id') return render(request, 'index.html',{'employee_list' : employee_list }) except Exception: return render(request, 'error.html',{'error':'Delete Operation Failed'})``` -
How to use environment variables from .env file in django views?
I have stored my secret token in .env file in my project root and I tried to use this token in django views.py like this import os from dotenv import load_dotenv load_dotenv() SECRET = os.environ.get('API_KEY') print(SECRET) def chat(request): url = 'https://slack.com/api/users.list' load_dotenv() SECRET = os.environ.get('API_KEY') print(SECRET) headers = {'Authorization' : 'Bearer SECRET '} r = requests.get(url, headers=headers) When I run through python manage.py runserver the token is being printing outside the function chat but inside the function it is not printing -
Convert numpy matrix to an image
Can someone help me to convert a sudoku grid ( a NumPy matrix with 81 numbers with shape(9,9)) to an image using open-cv? Most of the results I found on internet used the matrix as color representation. But, I want the image to show numbers. Ex: Example image I want to use that image to display it on my website. The NumPy matrix is generated using the back-end on Django? Also, If there is any better idea for this, can you please suggest it to me? -
Django-leaflet has reversed LngLat instead of LatLng
While trying to put a marker on django-leaflet, my marker reverses (Lat, Lng) to (Lng,Lat) in GeoDjango admin using django-leaflet. How can I correct admin.py widget form to Lat, Lng coordinates? from django.contrib import admin from django.contrib.gis.db import models as geo_models from leaflet.admin import LeafletGeoAdmin from .models import Apartment,User from django.contrib.auth.admin import UserAdmin from leaflet.forms.widgets import LeafletWidget LEAFLET_WIDGET_ATTRS = { 'map_height': '500px', 'map_width': '100%', 'display_raw': 'true', 'map_srid': 4326, } LEAFLET_FIELD_OPTIONS = {'widget': LeafletWidget(attrs=LEAFLET_WIDGET_ATTRS)} FORMFIELD_OVERRIDES = { geo_models.PointField: LEAFLET_FIELD_OPTIONS, geo_models.MultiPointField: LEAFLET_FIELD_OPTIONS, geo_models.LineStringField: LEAFLET_FIELD_OPTIONS, geo_models.MultiLineStringField: LEAFLET_FIELD_OPTIONS, geo_models.PolygonField: LEAFLET_FIELD_OPTIONS, geo_models.MultiPolygonField: LEAFLET_FIELD_OPTIONS, } -
Display data from external service in Django admin TabularInline
I have next django models class Service(models.Model): username = models.CharField(...) password = models.CharField(...) ... class Order(models.Model): service = models.ForeignKey('Service', on_delete=models.CASCADE, related_name='orders') number = models.CharField(...) creation_date = models.DateTimeField(...) ... And then in admin.py @register(Service) class ServiceAdmin(ModelAdmin): class OrderNewInline(TabularInline): ''' Display orders from remote service, external api, data-file ... List of orders to be imported ''' model = Order extra = 0 can_delete = False def has_change_permission(self, request, obj=None): return False def has_add_permission(self, request, obj=None): return False # Getting orders from remote service, external api, data-file ... # @param Service service - current service model instance # @return list - list of external orders def get_data(self, service, ...): ... class OrderInline(TabularInline): ''' Display orders already imported ''' model = Order ... inlines = [OrderNewInline, OrderInline] Please help me find solutions to the following questions: How to display orders in OrderNewInline from remote service, external api, data-file ... Create column in OrderNewInline with checkbox for mark orders have to be imported Add a button to OrderNewInline form to trigger orders import event -
django.core.exceptions.FieldError: Cannot resolve keyword 'students' into field. Choices are: exam, id, student, student_id, subject, test
I am building an online class, where students can check their result when they login to their account, i do not know how to go about quering the result from the database so as to be able to generate the result posted by the teacher for each students. Please how do i write the views.py I did some things but there was an error. This are my codes: class Result(models.Model): student = models.ForeignKey(Students, on_delete=models.CASCADE) test = models.FloatField(null=True, blank=True) exam = models.FloatField(null=True, blank= True) subject = models.CharField(max_length=3, choices=SUBJECT, null=True) class Meta: ordering = ["-student"] def get_total(self): return self.exam + self.test def __str__(self): return self.student.first_name class Students(models.Model): first_name = models.CharField(max_length=15, default='top') last_name = models.CharField(max_length=15, default='top') phone_number = models.IntegerField(default=0) email = models.EmailField() class_choice = models.CharField(max_length=3, choices=CLASS) last_accessed = models.DateTimeField(null=True, blank=True) user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) class Meta: ordering = ["last_name"] def __str__(self): return self.last_name def get_absolute_url(self): return reverse('students-detail', kwargs={'pk': self.pk}) -
Why can't I open a websocket connection to Django Rest API
I am using react hooks. When I try to establish a websocket connection to my local Django Rest Api, it says WebSocket connection to 'ws://127.0.0.1:8000/api/' failed: Error during WebSocket handshake: Unexpected response code: 200 -
How to segment WebM audio data
Consider a basic web application which livestreams audio from one client to the server and then back down to many other clients. So far so good, I setup a website that just does that using just JavaScript and Django (Python). However, there is a bug in my approach. If someone loads the website in the middle of a livestream the audio does not play. After lots of investigation, this is due to the lack of an initialization segment and not properly segmenting the audio data. A little more context here: Unable jump into stream from media recorder using media source with socket.io So before I heed the advice from StackOverflow and rip this WebM audio file apart byte by byte - has someone else done the hard work for me already? In Python, what is the easiest way for me to extract the initialization segment and each successive audio cluster from an WebM audio file? To be specific, the file is being created from the front-end using this mimeType: new MediaRecorder(mediaStream, {'mimeType': 'audio/webm; codecs="opus"',}); -
activating virtual environment on windows using powershell
Im following this tutorial: https://www.codingforentrepreneurs.com/blog/install-python-django-on-windows/ on step 7, I tried running pipenv shell in the same directory called cfehome, and also in a different directory, but it doesnt say the (cfehome) before the path, so i thought it hadnt been activated, but when I run the command again, it says environment already activated. Also, the tutorial states when i run pip freeze, i should get no output. but i do get an output with the names of different libraries. I followed all other steps and they gave the desired output so I dont know why this step is not? -
Django querysets filter in each object related in a many to many field?
i'm working in a view to filter some data and sent it back. I wanna filter by this FKs, alredy working on the FK user to FK account atribute of my Book model, now the problem is i have a ManyToMany field toand need to do the same filter for each of that authors. The what: if 'want_book' in requestData: if program_id != 'Programa educativo' and academy_id != 'Cuerpo academico': book_list = (Book.objects.filter( user__account__program=program_id).filter( user__account__academy=academy_id) |Book.objects.filter( authors__*foreachauthor*__program=program_id)).distinct() My models: class Book(models.Model): project = models.ForeignKey(Project, on_delete=models.PROTECT, verbose_name = "Proyecto") user = models.ForeignKey(UserSap, on_delete=models.PROTECT,verbose_name = "Autor principal") authors = models.ManyToManyField(Account,blank=True,verbose_name = "Otros Autores") ... class UserSap(AbstractBaseUser, PermissionsMixin): email = models.EmailField( max_length=100, verbose_name="Correo UABC", unique=True) account = models.OneToOneField( Account, on_delete=models.PROTECT, blank=True, null=True) class Academy(models.Model): name = models.CharField( max_length=100, verbose_name="Cuerpo académico", blank=True class Program(models.Model): name = models.CharField( max_length=100, verbose_name="Nombre del programa", blank=True) class Account(models.Model): program = models.ForeignKey( Program, on_delete=models.PROTECT, verbose_name="Programa educativo", blank=True, null=True) academy = models.ForeignKey( Academy, on_delete=models.PROTECT, verbose_name="Cuerpo académico", blank=True, null=True) any idea? -
how to make a JSON for this highchart - django app
I am working on django project I want to do a highchart dependency wheel but I don't know why the chart not showing , you will see my code below , in my dependencywheel.html I did already {%load static%} in the top <script> Highcharts.chart('container', { title: { text: 'Highcharts Dependency Wheel' }, accessibility: { point: { valueDescriptionFormat: '{index}. From {point.exped} to {point.destin}: {point.count}.' } }, series: [{ keys: ['exped', 'destin', 'count'], data: '{%url "data"%}', type: 'dependencywheel', name: 'Dependency wheel series', dataLabels: { color: '#333', textPath: { enabled: true, attributes: { dy: 5 } }, distance: 10 }, size: '95%' }] }); </script> this is my class in models.py class mail_item_countries_depend(models.Model): exped = models.CharField(max_length=100) destin = models.CharField(max_length=100) count = models.IntegerField(default=0) that's my views.py @login_required def depend(request): return render(request,'dependWheel.html',{}) def jsonDepend(request): dataset = mail_item_countries_depend.objects.all().values('exped','destin','count') data = list(dataset) return JsonResponse(data, safe=False) so the data looks like this : [{"exped": "MA", "destin": "AL", "count": 2}, {"exped": "MA", "destin": "BS", "count": 1}, {"exped": "AR", "destin": "DZ", "count": 2}, I already wrote a static data like this below to see if the dependency wheel gonna work and it worked data: [ ['Brazil', 'Portugal', 5], ['Brazil', 'France', 1], ['Brazil', 'Spain', 1], ['Brazil', 'England', 1], ['Canada', 'Portugal', 1], … -
Django, and React inside Docker inside a single Digital Ocean Droplet: 400 Bad Request for Django, React works fine
I have Django and React inside the same Docker container using docker-compose.yml and running this container inside a Digital Ocean Droplet running Ubuntu. When I navigate to http://my_ip_address:3000 which is the React app, it works just fine, but when I navigate to http://my_ip_address:8000 which is the Django app, I get a 400 Bad Request error from the server. project/back-end/Dockerfile FROM python:3.7 ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 WORKDIR /nerdrich COPY Pipfile Pipfile.lock /nerdrich/ RUN pip install pipenv && pipenv install --system COPY . /nerdrich/ EXPOSE 8000 project/front-end/Dockerfile # official node.js runtime for Docker FROM node:12 # Create and set the directory for this container WORKDIR /app/ # Install Application dependencies COPY package.json yarn.lock /app/ RUN yarn install --no-optional # Copy over the rest of the project COPY . /app/ # Set the default port for the container EXPOSE 3000 CMD yarn start project/docker-compose.yml version: "3" services: web: build: ./back-end command: python /nerdrich/manage.py runserver volumes: - ./back-end:/nerdrich ports: - "8000:8000" stdin_open: true tty: true client: build: ./front-end volumes: - ./front-end:/app - /app/node_modules ports: - '3000:3000' stdin_open: true environment: - NODE_ENV=development depends_on: - "web" command: yarn start project/back-end/nerdrich/.env ALLOWED_HOSTS=['165.227.82.162'] I can provide any additional information if needed.