Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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? -
ImproperlyConfigured at /admin/aldryn_newsblog/article/add/
Trying to follow the tutorial for integrating Django CMS into an existing application, Im also using cookiecutter. (the "project" is my homework) After installing aldryn-newsblog I have been stuck on the following error for quite some time : ImproperlyConfigured at /admin/aldryn_newsblog/article/add/ ImproperlyConfigured at /admin/aldryn_newsblog/article/add/ ImportError my_awesome_project.users.apps.UsersConfig: No module named 'my_awesome_project.users.apps.UsersConfig'; 'my_awesome_project.users.apps' is not a package Request Method: GET Request URL: http://localhost:8000/admin/aldryn_newsblog/article/add/ Django Version: 2.1.5 Exception Type: ImproperlyConfigured Exception Value: ImportError my_awesome_project.users.apps.UsersConfig: No module named 'my_awesome_project.users.apps.UsersConfig'; 'my_awesome_project.users.apps' is not a package Here is my backlog : Environment: Request Method: GET Request URL: http://localhost:8000/admin/aldryn_newsblog/article/add/ Django Version: 2.1.5 Python Version: 3.6.8 Installed Applications: ['django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', 'my_awesome_project.users.apps.UsersConfig', 'djangocms_admin_style', 'django.contrib.admin', 'cms', 'menus', 'treebeard', 'sekizai', 'filer', 'easy_thumbnails', 'mptt', 'djangocms_text_ckeditor', 'djangocms_link', 'djangocms_file', 'djangocms_picture', 'djangocms_video', 'djangocms_googlemap', 'djangocms_snippet', 'djangocms_style', 'djangocms_column', 'polls', 'polls_cms_integration', 'aldryn_apphooks_config', 'aldryn_boilerplates', 'aldryn_categories', 'aldryn_common', 'aldryn_newsblog', 'aldryn_people', 'parler', 'sortedm2m', 'taggit', 'crispy_forms', 'allauth', 'allauth.account', 'allauth.socialaccount', 'rest_framework', 'debug_toolbar', 'django_extensions'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', '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', 'cms.middleware.user.CurrentUserMiddleware', 'cms.middleware.page.CurrentPageMiddleware', 'cms.middleware.toolbar.ToolbarMiddleware', 'cms.middleware.language.LanguageCookieMiddleware', 'cms.middleware.utils.ApphookReloadMiddleware', 'debug_toolbar.middleware.DebugToolbarMiddleware'] Traceback: Exception Type: ImproperlyConfigured at /admin/aldryn_newsblog/article/add/ Exception Value: ImportError my_awesome_project.users.apps.UsersConfig: No module named 'my_awesome_project.users.apps.UsersConfig'; 'my_awesome_project.users.apps' is not a package Running : django-cms 3.6.0 Django 2.1.5 alabaster 0.7.12 aldryn-apphooks-config 0.5.2 aldryn-boilerplates 0.8.0 aldryn-categories 1.2.0 aldryn-common 1.0.5 aldryn-newsblog 2.2.1 aldryn-people 2.2.0 aldryn-translation-tools 0.3.0 … -
How to delete the current profile Image while uploading the new image of a authenticated user in django
I want to delete the existing profile image( named as profile_pic in models.py) while uploading the new profile pic of a authenticated user.. Below is the code samples of views.py , forms.py and models.py How to implement the functionality to delete the existing image while uploading new one in views.py or forms.py views.py class UpdateUserProfilePic(UpdateView): template_name = 'accounts/signup.html' form_class = forms.UserProfilePicUpdateForm success_url = reverse_lazy('test') def get_object(self): return self.request.user ---------x-------------------------------------------- forms.py class UserProfilePicUpdateForm(forms.ModelForm): class Meta: model = User fields = ('profile_pic',) ---------x-------------------------------------------- models.py class User(AbstractBaseUser): ....... ....... profile_pic = models.ImageField( upload_to='profile_pics', default='default-profile.png') ....... -
How do I send a value of a variable from view to form in django?
I want a customized dropdown list as a choice field for a variable. This list depends on another variable in form How can I send a variable value to the variable in forms views.py z= somelist class HomeView(TemplateView): template_name='charts.html' form = HomeForm(z = z) def get(self, request): form = HomeForm() return render(request, self.template_name, {'form':form}) def post(self,request): form=HomeForm(request.POST) if form.is_valid(): text_11 = form.cleaned_data['post11'] global e e=text_11 text_1 = form.cleaned_data['post_1'] global z z=text_1 text = form.cleaned_data['post'] global b b=text text1 = form.cleaned_data['post1'] global c c=text1 text2 = form.cleaned_data['post2'] global d d=text2 args = {'form':form, 'text_11':text_11,'text_1':text_1,'text':text, 'text1':text1, 'text2':text2} return render(request, self.template_name, args) my forms.py class HomeForm(forms.Form): post11=forms.ChoiceField(choices=((None,None),('लिंग :','sex :'),('शिक्षण:','education:'))) post_1 = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple,choices=**somelist**) post = forms.ChoiceField(choices=((None,None),('लिंग :','लिंग :'),('शिक्षण:','शिक्षण:'),('जात :','जात :'))) post1 = forms.ChoiceField(choices=((None,None),('लिंग :','लिंग :'),('शिक्षण:','शिक्षण:'))) post2 = forms.ChoiceField(choices=((None,None),('bar','bar'),('horizontalBar','horizontalBar'))) I want the variable to be here post_1 = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple,choices=**somelist**) Thanks in advance :) -
Django save aggregation in master/detail (many to one relationship)?
I have two models, Order and OrderRow (1:n). What I would like is when something changes on the OrderRow (added, removed, price change, etc.) that that "effect" is calculated to the parent Order. In this case, sum the total of all the OrderRow in Order. The OrderRow (a admin.TabularInline subclass) is setup as inlines on Order. I did implement the django.db.models.signals.post_save but the problem here is that the Order post_save is fired before the OrderRow updates. Is there any nice way (besides implementing a db trigger) for updating this the 'django-way' ? All this under Django Admin