Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django DB Routers
My django application will connect with 3 diffrent databases (SQLLite as default, postgresql for product and manufacturer database, MSSQL for Funds database) for 3 diffrent app (product, manufacturer, funds) I have created 3 routers.py file in each app to route the read, write operations depending on the app_lable name. On my settings file I have created a DATABASE_ROUTERS configuration as below DATABASE_ROUTERS = [ "product.routers.productdbrouter","manufacturer.routers.manufacturerdbrouter", "funds.routers.fundsdbrouter", ] Now when I try to access the application it always tries to find the table from the first router (product.routers.productdbrouter in this case) and if the table is missing then it fetches from the default router (SQLLITE). Any suggestion on what Iam missing on the configuration? -
Stream with OpenCV from client to Django server
I'm looking for a solution for the following: I have a server with a Django backend to be used as a kind of chat app with a chat room that will be used to connect two clients. For that I'm using Django Channels. Client A connects to the chat room and is able to send messages to client B using this toy example (running in client B): import asyncio import websockets import json ws_url = "ws://IP_ADDRESS:PORT/ws/chat/loby/" async def command_receiver(): async with websockets.connect(ws_url) as websocket: while True: message = await websocket.recv() message = json.loads(message) print("Received: ",message["message"]) asyncio.get_event_loop().run_until_complete(command_receiver()) Now I want that client B streaming its webcam using for example OpenCV in response to client A message. In the same python script, I want to capture the webcam stream using, for example, this solution. It would be something like to this: import asyncio import websockets import json import cv2 import numpy as np ws_url = "ws://IP_ADDRESS:PORT/ws/chat/loby/" async def command_receiver(): async with websockets.connect(ws_url) as websocket: while True: message = await websocket.recv() message = json.loads(message) if message["message"] == "send_stream": cap = cv2.VideoCapture(0) currentFrame = 0 while(True): # Capture frame-by-frame ret, frame = cap.read() # Handles the mirroring of the current frame frame = cv2.flip(frame,1) … -
Django Bash completion not working on manage.py
I am trying out the django_bash_completion script provided by Django but can't use it with python manage.py command. I am trying out the django_bash_completion script provided by Django. I have added it to active script in the virtual environment. It works with django-admin but can't use it with python manage.py command. virtualenv -p python3 venv echo "source /path/to/.django_bash_completion" >> venv/bin/active active django-admin<tab><tab> python manage.py<tab><tab> For django-admin it shows all options like check, makemigrations, migrate runserver etc but when I run python manage.py it gives manage.py: command not found. Any idea why and how can I solve it? I am running bash on Ubuntu 18.04 -
Error whie install psycopg2 on ubuntu server 16.04
error: command 'x86_64-linux-gnu-gcc' failed with exit status 1 ---------------------------------------- ERROR: Command errored out with exit status 1: /home/mosi/venv/bin/python3.6 -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-im9_x6c8/psycopg2/setup.py'"'"'; file='"'"'/tmp/pip-install-im9_x6c8/psycopg2/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(file);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' install --record /tmp/pip-record-jyz3lis6/install-record.txt --single-version-externally-managed --compile --install-headers /home/mosi/venv/include/site/python3.6/psycopg2 Check the logs for full command output. -
How to exclude empty values in an AND queryset whitout writing if else statements
For a real-estate listing site I have a search form with multiple inputs. The user can use one or many fields to filter his search results. The more fields are filled in the more detailed the search should get. For example: If you only input the zip code all listings that match the zip code should be shown, if you input the zip code and the room number only listings that match both should be shown. My forms.py looks like this: from django import forms from .models import Property class PropertyForm(forms.Form): zip_code = forms.CharField(required=False) rooms = forms.CharField(required=False) Because I need a AND search I had to write a series of conditions in my ListView to query the results: My views.py looks like this: class ListPageView(ListView): template_name = 'property_list.html' model = Property def get_queryset(self): plz = self.request.GET.get('plz') rooms = self.request.GET.get('rooms') if plz and not rooms: object_list = Property.objects.filter(zip_code__exact=plz) elif rooms and not plz: object_list = Property.objects.filter(rooms__exact=rooms) elif plz and rooms: object_list = Property.objects.filter( Q(zip_code__icontains=plz) & Q(rooms__exact=rooms) ) else: object_list = self.model.objects.none() return object_list For only two input fields this would suffice but if I add more input fields I quickly have to write a lot of queries. Is there a better … -
Trying to save with model formset factory getting 'list' object has no attribute 'event'
I'm trying to save a related model field via Django model_formset but it's giving me this error AttributeError at /events/event/52/detail 'list' object has no attribute 'fields' anyone ever encountered this? and how to solve it. thanks View def event_detail(request, pk): event = get_object_or_404(Event, pk=pk) TicketFormSet = modelformset_factory(Ticket, exclude=('event',), extra=1, max_num=3) if request.method == 'POST': ticket_form = TicketFormSet(request.POST) if ticket_form.is_valid(): ticket_obj = ticket_form.save(commit=False) # ticket_obj.event = event ticket_obj.fields['event'].queryset = event ticket_obj.save() else: ticket_form = TicketFormSet() return render(request, 'events/event/event_detail.html', {'event': event, 'formset': ticket_form}) Model class Ticket(models.Model): event = models.ForeignKey(Event, on_delete=models.CASCADE) name = models.CharField(max_length=120) quantity = models.SmallIntegerField() price = models.FloatField() def __str__(self): return '{} {}'.format(self.event.name, self.name) -
Force to run delayed task Celery
I have a celery task with countdown, and I want to force this task to run. task_id = uuid() timer.apply_async( args=(self.room_group_name, cache.get(f'{self.room_name}_round'), cache.get(f'{self.room_name}_round') > self.total_rounds ), countdown=self.timer' task_id=task_id ) now I revoke this task and create another task. Is there any possibility to force run celery task with countdown? -
Call a Django view from JavaScript
Say I'm writing a web app, web shop to sell antique coins, and I have an HTML combobox (<select>) and upon selection (say, I selected 'gold') I want to redirect to a specific Django view, how can I do that? My guess is JavaScript, but I'm not sure how to properly construct a URL to the desired Django view. -
Django with NoSQL
I want to create a website using django to visualize data for companies, and I have the data in json file represented as: [{'label': 'BMW', 'gain': [{'cash': 198, 'visa': 923, 'year': 1988}, {'cash': 112, 'visa': 313, 'year': 1989}], 'type': 'automobile'}] Is it better to create two tables for each year or I should use NoSQL database with django? I don't have any experience with NoSQL, can you tell which is easier to use? -
Why does template inheritance in Django not show error?
I'm not seeing an error when template inheritance seems to fail. I don't see content from the child template but I don't see a 'TemplateNotFound' error. If I change the path to the parent template to 'notthefilename.html' I still don't see an error. Is there a way to make template inheritance fail noisily? I have no idea why this is not working even though I have a similar inheritance in a adjacent folder that is working as expected. generic_create.html The text 'hello2' is rendering. {% extends "base.html" %} {% load crispy_forms_tags %} {% block content %} <div style= "padding-top: 30px"> <form method="post">{% csrf_token %} {% if model_name == 'TransactionsTable' %} <div> {% block transactions_create %} hello2 {% endblock transactions_create %} </div> {% else %} {{ form |crispy }} {% endif %} <div id="container"> <input type="submit" class="btn btn-default" value="Save"> <a href="{{ view.get_success_url }}" class="btn btn-default">Cancel</a> <div> </form> </div> {% endblock content %} transactions_create.html - The content 'Hello1' is not rendering {% extends "generic_create.html" %} {% load static %} {% block transactions_create %} Hello1 {% endblock transactions_create %} -
How to remove the unspecified space between root and include url in django 2.2
I am trying to create a Django website. I have specified the path to one of my apps. But I am getting an unspecified space in the pattern.I am using Django 2.2. screenshot of the django debug page my base urls.py file from django.contrib import admin from django.urls import include, path urlpatterns = [ path('', include('homepage.urls')), path('account/', include('account.urls')), path('admin/', admin.site.urls), path('db/', include('dashboard.urls')), ] my dashboard/urls.py file from django.urls import include, path from .import views urlpatterns = [ #author dashboard path('authordboard/<int:auth_id/',views.author_dboard, name='author_details'), #reviewer dashboard path('reviewdboard/<int:re_id/',views.author_dboard, name='reviewer_details'), ] I have included the dashboard app in the settings.py file. Please help! Thanks in advance! -
Host a Django Application on Digital Ocean with ssl obtained from Let's Encrypt Certbot as at Sept 2019
I'm trying to enable ssl on my domain name and after I follow the steps on the certbot website to set up ssl for my new domain I get an error port 80 is already in use when I run python3 manage.py runserver 0.0.0.0:80. I'm using nginx and that's what shows up on my index page. I want to test out the https before I bind with gunicorn to that port but would it work then. I tried to do this before two weeks ago and it worked perfectly fine. Installed nginx and ssl cert and ran python3 manage.py runserver 0.0.0.0:80 and it was working -
Standard way to model customer data
I am building a saas site which shall serve the end users to keep their clients/customers data. These clients may optionally have an account on the website to log in where they can submit their data to the professionals and also check up on the status updates on their cases. My question is, how should I store the personal contact details of these customers. If I think of storing this in the in-built Users table then the argument is that not all the clients shall log in and actually become a user of the website. The contact data is needed to be stored in both the cases, whether a client becomes a site user or not. Right now I am thinking, I should have a separate model/table for client's contact data. In the event that a client does create an account on the site, I should copy that data to the User's table. But then data would be repeated in two places. What is the standard way of doing this? Isn't the Users table only/usually for people who actually use the website? -
How to display queryset single field value in django template?
Here I returned the only one model field value using the values() method but I got problem while displaying this field value in template. How can I do it ? views.py image = MyModel.objects.filter(active=True).values('bg_image').last() print(image) #this is working fine return {'image':image} I tried these in template {{image.login_bg_image.url}} #didn't worked {{login_bg_image.url}} {{image.url}} #didn't worked either -
Django - Get File Info from File Field
I have a django file field for audio files and I want to ask if it is possible to get file information like file size? I would also need the length of the audio file. Thank you for any suggestion/resource on this topic -
Timeout when reading response headers from daemon process even after setting WSGIApplication group to Global
I am hosting a Django based webpage locally using Apache. However, I am getting the following error : Timeout when reading response headers from daemon process 'office':var/www/office/office/wsgi.py. I tried adding the line WSGIApplicationGroup %{GLOBAL} to the conf file, but still getting the same error. This is my .conf file. WSGIPythonPath /var/www/office ServerName office.org LoadModule wsgi_module /usr/lib/apache2/modules/mod_wsgi.so WSGIApplicationGroup %{GLOBAL} <VirtualHost 0.0.0.0:80> ServerAlias www.office.org DocumentRoot /var/www/example.com/public_html <Directory /var/www/example.com> Require all granted </Directory> <Directory /var/www/office/office> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess office python-home=/var/www/venv python-path=/var/www/office WSGIProcessGroup office WSGIScriptAlias /verify /var/www/office/office/wsgi.py process-group=office ErrorLog /var/www/logs/error.log CustomLog /var/www/logs/custom.log combined </VirtualHost> This is wsgi.py file: """ WSGI config for office project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/2.0/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "office.settings") application = get_wsgi_application() -
Django: Merging n raw query set results
With the results of a Django raw query set using a query such as this: for employee in employees: staff = Staff.objects.raw('Long query... WHERE employee_id= %s', [employee.id]) I created a list, then created a dictionary. final_list = [] for s in staff: a = { 'first_name' : s.first_name, } final_list.append(dict(a)) print(final_list) Resulting in this: [{'first_name':u'John'}, {'first_name':u'Jill'}] [] [{'first_name':u'James'}, {'first_name':u'Susan'}] [{'first_name':u'Bill'}] How can I merge the results to get something like this: [{'first_name':u'John'}, {'first_name':u'Jill'}, {'first_name':u'James'}, {'first_name':u'Susan'}, {'first_name':u'Bill'}] -
Search doesn't return results in Django-rest-framework
I am recently building a web app backend with Django-rest-framework. I am trying to build a search functionality where the user will type in a location name and all results that contain the name will be displayed. I am using icontains and Q. My test search view is as below: class test_search(APIView): def post(self, request, *args, **kwargs): serializer_class = customer_location title = json.loads(request.body).get('title') queryset = Customers.objects.filter(Q(title__icontains=title)) http_method_names = ['get'] I am able to see a page which asks me to enter the location name but when I enter the name and click POST nothing happens. I want to display the values present in the Customer model, customer_location serializer which match the location name. I am using icontains as I want to return all values which contain it. What am I doing wrong? How to display the matched results? -
What's the best way to implement django models for this unique scenario
I'm working on a project using Django(2.2) and Python(3.7) in which I have to implement models for a specific scenrio: I have a Vote in which we have five questions like: DELIVERING VALUE EASY TO RELEASE FUN HEALTH OF CODEBASE TEAMWORK and each of these questions has options in the form of dropdown as: -- Select -- --helpful-- --not helpful-- --disaster-- and all of these votes will belong to a group and later I need to perform some aggregations to get the total no of votes for of these options (like helpful) against each question (like DELIVERING VALUE). Here's how currently I have implemented this scenario in Django models: From models.py: class UserGroup(models.Model): email = models.EmailField(primary_key=True) group = models.CharField(max_length=250, default='notingroup') def __str__(self): return self.group VOTE_CHOICES = ( ('helpful', "helpful"), ('meh', 'meh'), ('disaster', 'disaster') ) class VotingValues(models.Model): value1 = models.CharField(max_length=40) value2 = models.CharField(max_length=40) value3 = models.CharField(max_length=40) value4 = models.CharField(max_length=40) value5 = models.CharField(max_length=40) score1 = models.CharField(choices=VOTE_CHOICES, max_length=20) score2 = models.CharField(choices=VOTE_CHOICES, max_length=20) score3 = models.CharField(choices=VOTE_CHOICES, max_length=20) score4 = models.CharField(choices=VOTE_CHOICES, max_length=20) score5 = models.CharField(choices=VOTE_CHOICES, max_length=20) user = models.EmailField(max_length=255) group = models.CharField(max_length=250, default='notingroup') date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.user + ' \'s ' + 'vote in ' + self.group is there a better approach … -
Python list has 3 elements but I can only access the last element
I am processing a POST request in a django view and am expecting a list of strings in one of the dictionary elements. I'm using Pycharm to debug the code and I can see that in the dictionary, 3 values are returned but when I try to access that dictionary element, I can only access the last item in the list. I'm hoping it's a typecast issue of some sort perhaps? The filepond dictionary is a 3rd party java library I'm using so I have no control over how it gets POSTed back to django. -
"manage.py startapp" doesn't create db.sqlite3
I'm following an online tutorial in order to learn Django/Python. I'm using PyCharm Community Edition as my IDE. On Windows 10. When I run python manage.py startapp myapp at the (venv) prompt in terminal window , no error is shown, and \myapp folder is created with the expected content. However, the file db.sqlite3 is not created, and I can't follow through the rest of the tutorial. What might be going wrong here? Thank you very much. -
Accessing elements in a list in a Queryset
I am saving a elements from a list from from a page on my Django site The lists look like this when saved to the Database ['Precipitaciones', 'Pirineo', 'aragonés', 'catalán'] ['activarán', 'tormentas', 'ibérica,', 'descartan', 'chubascos', 'dispersos,', 'temperaturas'] I want to be able to access all the elements but when I run a queryset with context I get returned <QuerySet [("['Precipitaciones', 'Pirineo', 'aragonés', 'catalán']", ("['activarán', 'tormentas', 'ibérica,', 'descartan', 'chubascos', 'dispersos,', 'temperaturas']")]> Which to me looks like a stings inside a list inside a string inside a tuple inside a Queryset. So I can't workout how to access a single element when I try → queryset.0.0 I have returned to the screen Which returns the first element of the first element but I don't know how to get the first string of that element if I use → queryset.0.0.0 I just get the first element again which is a bracket [ Any help appreciated or some documentation where I can discover more about it would be great. -
What is the best to render multiple google map markers in DJANGO template
I have looked into similar questions but they have different implementations method therefore i am kind of stuck trying to render a queryset from the view template to be displayed on Google map. models.py class Location(models.Model): name = models.CharField(max_length=250, blank=False) description = models.TextField(max_length=1000, null=True) address = models.CharField(max_length=1000) longitude = models.DecimalField(max_length=15, decimal_places=8) latitude = models.DecimalField(max_length=15, decimal_places=8) views.py def index(request): locations = Location.objects.all() context = {'locations':(locations)} return render(request, 'core/index.html', context) html {% for activity in activities %} <script type="text/javascript"> var locations = [ ['Stadtbibliothek Zanklhof', 47.06976, 15.43154, 1], ['Stadtbibliothek dieMediathek', 47.06975, 15.43116, 2], ['Stadtbibliothek Gösting', 47.09399, 15.40548, 3], ['Stadtbibliothek Graz West', 47.06993, 15.40727, 4], ['Stadtbibliothek Graz Ost', 47.06934, 15.45888, 5], ['Stadtbibliothek Graz Süd', 47.04572, 15.43234, 6], ['Stadtbibliothek Graz Nord', 47.08350, 15.43212, 7], ['Stadtbibliothek Andritz', 47.10280, 15.42137, 8] ]; var map = new google.maps.Map(document.getElementById('map'), { zoom: 13, center: new google.maps.LatLng(47.071876, 15.441456), mapTypeId: google.maps.MapTypeId.ROADMAP }); var infowindow = new google.maps.InfoWindow(); var marker, i; for (i = 0; i < locations.length; i++) { marker = new google.maps.Marker({ position: new google.maps.LatLng(locations[i][1], locations[i][2]), map: map }); google.maps.event.addListener(marker, 'click', (function(marker, i) { return function() { infowindow.setContent(locations[i][0]); infowindow.open(map, marker); } })(marker, i)); } </script> {% endfor %} I am just stuck on how and where to place the tags … -
Django App TypeError django.views.i18n.javascript_catalog
I have an django app and this app running in my local server. But it can not run my digitalocean server. When enter this app, give this error Internal Server Error. I am using git service and I tested lots of time same codes in my local server. Also I tried to run manage.py runserver in digitalocean and give this error. I am using git and these code are the same but it is not running app_name : writed here my app name urls.py js_info_dict = { 'domain': 'djangojs', 'packages': ('app_name',), } urlpatterns = [ ... url(r'^admin/', include(admin.site.urls)), ... url(r'^jsi18n/$', 'django.views.i18n.javascript_catalog', js_info_dict), ] command ./manage.py runserver error also gunicorn.log show same error Unhandled exception in thread started by Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/django/utils/autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/django/core/management/commands/runserver.py", line 121, in inner_run self.check(display_num_errors=True) File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 374, in check include_deployment_checks=include_deployment_checks, File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 361, in _run_checks return checks.run_checks(**kwargs) File "/usr/local/lib/python2.7/dist-packages/django/core/checks/registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "/usr/local/lib/python2.7/dist-packages/django/core/checks/urls.py", line 14, in check_url_config return check_resolver(resolver) File "/usr/local/lib/python2.7/dist-packages/django/core/checks/urls.py", line 24, in check_resolver for pattern in resolver.url_patterns: File "/usr/local/lib/python2.7/dist-packages/django/utils/functional.py", line 35, in get res = instance.dict[self.name] = self.func(instance) File "/usr/local/lib/python2.7/dist-packages/django/urls/resolvers.py", line 313, in url_patterns patterns = getattr(self.urlconf_module, … -
how to solve this problem with heroku TypeError: 'set' object is not subscriptable
every time I try to deploy a project I have this problem actually django tells me that the mistake come from "" DATABASES['default'].update(db_from_env) TypeError: 'set' object is not subscriptable"""