Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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""" -
DJANGO ADMIN ACTIONS
kindly anyone say ans to my query: (http://127.0.0.1:8000/admin/certificates/usercertificates/->) in thiz link , if i select some list it should be generate and show as pdf in django admin actions -
How to use django url in ajax?
How to call django function using ajax with id (or pk). $.ajax({ url: '{% url app:order_edit %}', type:"POST", async:false, data: {order:order, product:product, customer:customer, qty:qty, uom:uom, des:des}, success:function(data){ } }); views.py def order_edit(request, obj_id): print("Obj Id is:",obj_id) if request.method == 'POST': form = OrderForm(request.POST) if form.is_valid(): #operations return render(request, 'order_view.html', {'form': form}) return render(request, 'order_view.html', {'form': form}) return render(request, 'order_view.html', {}) urls.py path('orderedit/<int:obj_id>/', views.order_edit, name="order_edit"), how to call this function Anyone Help me in this issu. Thanks in advance -
Getting attribute error ='NoneType' object has no attribute 'content'
I am adding api to my views.py in my app. and facing some attribute error from django.shortcuts import render def home(request): import requests import json api_request = request.POST.get("https://min-api.cryptocompare.com/data/v2/news/?lang=EN") api = json.loads(api_request.content) return render(request, 'home.html', {"api": api}) Expected output is the data which is being fetch from the api. Getting error AttributeError at / 'NoneType' object has no attribute 'content' -
How to send notification from admin to user in Django
I am building an online shopping website using Django framework. I want to implement an order approval system where Django Admin will approve the order request from the user and at that time a notification or message will be sent to the user. Currently I have an order request model with an order status field. When the value of that field will be set approved by the admin a notification will be sent to that user. I want a push notification system here. How can I implement this in Django? -
500 internal server error when changing the db from sqlite to postgres with django and nginx
I am wondering about some things, i followed this tutorials setting up server I am currently using django 2.2, psycopg2 2.8.3, uwsgi 2.0.18. I am able to migrate models to db but the nginx server failed to communicate with it. I added local host with port 5432 to cors header. does this a permission issue, as nginx runs with a user? or it is something else? should i use https for local host in cors header allowed hosts as it is only allowed by nginx and django? -
Error when upload file CVS file in django
When I upload CSV file appeared this error enter image description here -
How to access form element in javascript function?
I'm trying to access an element in javascript function so as to autocomplete the user search, using autocomplete API. My javascript code: <script> $(function() { $("#q").autocomplete({ source: "/api/get_drugs/", minLength: 2, }); }); </script> My reference for search. My Form: <form id = "myForm" method="GET" action="{% url 'search' %}"> <input style="width:340px;height:37px;" size="30" type="text" id = 'q' name = 'q' placeholder="Search products or categories"/> <input type="submit" value="Search" > </form> Here the input target field has id and name- 'q'. -
Django: Access images via templates, stored on AWS S3
To keep performance I outsourced a machine learning task to AWS Lambda. The result are images saved in an S3 bucket. My challenge is now: How can I access these images through my .html templates? My framework is Django. <img src="s3://BUCKET_NAME/188.png" alt=""> So far I only get access denied. I could make the file public, but my initial goal was to only let my page access these files. Is there a simple solution to grant access without setting up S3Storage (I already have that, but I use a separate account for this machine learning task). -
Wagtail/Django translations not showing
I am trying to develop bilingual Wagtail site, and having problems getting translations work. Translations compiled fine to myproject/myproject/locale/fi/LC_MESSAGES/django.mo however, translations in my templates don't show. also when i do, >>> from django.utils.translation import activate >>> from django.utils.translation import get_language >>> get_language() 'en-us' >>> activate("fi") >>> get_language() 'fi' >>> ugettext("PHOTOS") 'PHOTOS' settings file: MIDDLEWARE = [ 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware', 'wagtail.core.middleware.SiteMiddleware', 'wagtail.contrib.redirects.middleware.RedirectMiddleware', ] LANGUAGES = ( ('en', _('English')), ('fi', _('Finnish')), ) LANGUAGE_CODE = 'en-us' USE_I18N = True USE_L10N = True USE_TZ = True LOCALE_PATHS = ( os.path.join(PROJECT_DIR, 'locale'), ) django.po: #: .\mysite\templates\base.html:63 msgid "PHOTOS" msgstr "KUVIA" base.html: {% trans "PHOTOS" %} any ideas how to troubleshoot further?