Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I am using django tables 2 and trying to export my table following the official documentation
I have followed the official documentation of django tables 2 but it is not working I dont know why views.py from django.shortcuts import render from django_tables2 import RequestConfig from django.template.response import TemplateResponse from .models import Customer from .tables import CustomerTable from .tables import TableView from django_tables2.export.export import TableExport def user_profile(request): table= CustomerTable(Customer.objects.all()) RequestConfig(request,paginate={'per_page':15}).configure(table) return render(request, 'home.html', {'table': table}) def TableView(request): table = CustomerTable(Customer.objects.all()) RequestConfig(request).configure(table) export_format = request.GET.get('_export', None) if TableExport.is_valid_format(export_format): exporter = TableExport(export_format, table) return exporter.response('table.{}'.format(export_format)) return render(request, 'table.html', { 'table': table }) my html template {% extends 'base.html' %} {% block content %} {% load render_table from django_tables2 %} {% load querystring from django_tables2 %} <!doctype html> <html> <head> <title>List of Customers</title> </head> <body> {% querystring '_export'='csv' %}home {% for format in table.export_formats %} <a href="{% querystring '_export'=format %}"> download <code>.{{ format }}</code> </a> {% endfor %} <p margin-bottom:500px;> </p> <div style="width: 2500px; height: 600px; overflow-y: scroll;"> <div id ="users"> <input class="search" placeholder="Search" /> {% render_table table %} {% endblock %} </div> </div> </body> urls.py urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', user_profile, name="user_profile"), url(r'^$', TableView, name="TableView"), ] tables.py import django_tables2 as tables from .models import Customer from django_tables2.export.views import ExportMixin from .models import Customer class CustomerTable(tables.Table): class Meta: model … -
The view accounts.views.register didn't return an HttpResponse object. It returned None instead
i have tried all possible solutions found online but none seems to help me eliminate this error message. from django.shortcuts import render, redirect from accounts.forms import RegistrationForm def home(request): numbers = [1,2,3,4,'A','B','C'] name = 'SimiDev' args = {'myname': name, 'numbers': numbers} return render(request,'accounts/home.html',args) def register(request): if request.method =='POST': form = RegistrationForm(request.POST) if form.is_valid(): form.save() return redirect('/accounts') else: form = RegistrationForm() args = {'form': form} return render(request, 'accounts/reg_form.html',args) -
Django static and media files not loading on Firefox Focus when served from S3
Django static and media files are not loading on Firefox Focus when served from S3 using nginx and using HTTPS. Everything works well if I use a different browser or serve static files from localhost. There's and option in Focus called "Block other content trackers". If I turn that off, Focus works as expected, loading all the files properly. So I understand that my files are being blocked for some reason but I don't know why. And since most of the websites are working fine on Focus, I guess my website should work too. -
Django: How to retrieve a particular item for specific user from a model?
How can I retrieve a specified field for a particular user in Django? I got user: A, B, C and user A got 10 url records in the database. The problem is how to retrieve the 10 url records of user A? Thank you so much.models.py class Bookmark(models.Model): url = models.CharField(max_length=500) shortlisted_by = models.ForeignKey(User, related_name='bookmark') shortlisted_date = models.DateTimeField(auto_now_add=True) -
Django rest framework timefield input format
After hours of searching , i found many post that is related but wasnt able to help. What i want to do is input eg: 10:30 AM into the timefield. In the django rest framework api on browser, it is using this 10:30 AM format ('%I:%M %p'). But when i am using postman to test it, the output is in 24hr format ('%H:%M:%S'). I also tried to using 10:30 PM as input but the output i get is 10:30:00 instead of 22:30:00. Many of the answer i found is change the timefield format in settings.py by using this line TIME_INPUT_FORMATS = ('%I:%M %p',) but it doesnt work for me. Sorry for my inexperience on django rest framework as i am still learning. Here is the screenshot of the result. On browser API: On postman: -
Log formatting in django for kibana
In my django app, I'm trying to log the exception messages in dictionary format. The keys of the dictionary would be used in kibana for filtering. For example an exception message like Could not get details for student <student> in school <school> should look like { 'message': 'Could not get details for student <student> in school <school>', 'student': <student>, 'school': <school> } Above I would be using value in to get the school related exception details in my kibana. I've looked into logstash_formatter. It does not parse the exception message for me. With my approach I'm ending up creating dictionaries with certain key, value pairs at all the places wherever I'm logging and it really doesn't look good. Another option I thought of is adding a wrapper on top of my django logging and implement debug, info etc methods inside it and use it at all the places I'm logging. Not sure if that's the right way too. This can also be achieved using grok patterns on logstash side but for certain maintainability reasons can't do it too. What are the other options to achieve this. suggestions ? -
How to set multiple Django site on VPS using Apache?
I have Deploy a Django application on VPS using Apache and mod_wsgi. Without a Domain name. One can access the site just by typing IP address on browser. Now I have another application I want to configure this second application with similar IP address, how can I set this. So that if some one can access both the site just by typing xx.xxx.xxx.63/app1 or xx.xxx.xxx.63/app2 On browser.. bellow is my "000-default.conf" file: <VirtualHost *:80> # The ServerName directive sets the request scheme, hostname and port that # the server uses to identify itself. This is used when creating # redirection URLs. In the context of virtual hosts, the ServerName # specifies what hostname must appear in the request's Host: header to # match this virtual host. For the default virtual host (this file) this # value is not decisive as it is used as a last resort host regardless. # However, you must set it for any further virtual host explicitly. #ServerName www.example.com Alias /static /home/myproject/DATAPLO/static <Directory /home/myproject/DATAPLO/static> Require all granted </Directory> <Directory /home/myproject/trytable> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess myproject python-path=/home/myproject:/home/myproject/myprojectenv/lib/python2.7/site-packages WSGIProcessGroup myproject WSGIScriptAlias / /home/myproject/trytable/wsgi.py ServerAdmin webmaster@localhost DocumentRoot /var/www/html # Available loglevels: trace8, ..., trace1, debug, … -
Allow django rest api to process Not raw Json
I wrote simple django app to store emails, when I send raw data it works perfectly, meanwhile when use postman or request.post(url, data: {'from':'somebody', 'to': 'someboy' ...} ) I get No JSON object could be decode error in the entranteJson = json.loads(entrante) line. @csrf_exempt def email_create(request): """ List all code pedidos, or create a new pedido. """ if request.method == 'GET': emais = Email.objects.all() serializer = EmailSerializer(emais, many = True) return JsonResponse(serializer.data, safe = False) elif request.method == 'POST': entrante = request.body.decode("utf-8") entranteJson = json.loads(entrante) serializer = EmailSerializer(data=entranteJson) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data, status=201) return JsonResponse(serializer.errors, status=400) Somebody has any suggestion to can send data via form-data ? I really appreciate it very much. -
NoReverseMatch at /answer/ Reverse for 'detail' with keyword arguments '{'pk': 1}' not found. 1 pattern(s) tried: ['answer/$(?P<pk>\\d+)/$']
for some reason I cannot seem to solve this bug. , any help will be appreciated this is the models.py def get_absolute_url(self): # return f"/question/{self.slug}" return reverse('qna:detail', kwargs={'pk': self.pk}) qna/Urls.py url(r'^$', AnsListView.as_view(),name='list'), url(r'^create$', AnsCreateView.as_view(),name='create'), url(r'^(?P<pk>\d+)/$', AnsDetailView.as_view(),name='detail'), main/url.py url(r'^answer/$',include('qna.urls', namespace='qna')), Error when try to load http://127.0.0.1:8000/answer/ NoReverseMatch at /answer/ Reverse for 'detail' with keyword arguments '{'pk': 1}' not found. 1 pattern(s) tried: ['answer/$(?P<pk>\\d+)/$'] Request Method: GET Request URL: http://127.0.0.1:8000/answer/ Django Version: 1.11.2 Exception Type: NoReverseMatch Exception Value: Reverse for 'detail' with keyword arguments '{'pk': 1}' not found. 1 pattern(s) tried: ['answer/$(?P<pk>\\d+)/$'] Exception Location: C:\Users\prash\Desktop\prashantks\pksproject\lib\site-packages\django\urls\resolvers.py in _reverse_with_prefix, line 497 -
Removed id field from my model by mistake
I accidentally removed id field from the model. Now I want to undo it. I am getting Integrity Error - datatype mismatch error. But python manage.py makemigrations and python manage.py migrate are running well with no problems. I have also deleted the model and created it once again. After creating, the 0001_initial.py file that gets created on migrating the model contains the default id column. But still I am not able to overcome my problem. The full error trace is as follows: Internal Server Error: /drizzlelore/createEvents Traceback (most recent call last): File "C:\Users\eloixir\Desktop\mysite\myvenv\lib\site-packages\django\db\backe nds\utils.py", line 65, in execute return self.cursor.execute(sql, params) File "C:\Users\eloixir\Desktop\mysite\myvenv\lib\site-packages\django\db\backe nds\sqlite3\base.py", line 328, in execute return Database.Cursor.execute(self, query, params) sqlite3.IntegrityError: datatype mismatch The above exception was the direct cause of the following exception: ngo\dTraceback (most recent call last): File "C:\Users\eloixir\Desktop\mysite\myvenv\lib\site-packages\django\core\han dlers\exception.py", line 41, in inner response = get_response(request) File "C:\Users\eloixir\Desktop\mysite\myvenv\lib\site-packages\django\core\han dlers\base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\eloixir\Desktop\mysite\myvenv\lib\site-packages\django\core\han dlers\base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\eloixir\Desktop\mysite\mysite\home\views.py", line 54, in creat e_event event = form.save() File "C:\Users\eloixir\Desktop\mysite\myvenv\lib\site-packages\django\forms\mo dels.py", line 463, in save self.instance.save() File "C:\Users\eloixir\Desktop\mysite\myvenv\lib\site-packages\django\db\model s\base.py", line 807, in save force_update=force_update, update_fields=update_fields) File "C:\Users\eloixir\Desktop\mysite\myvenv\lib\site-packages\django\db\model File "C:\Users\eloixir\Desktop\mysite\myvenv\lib\site-packages\django\db\model s\base.py", line 837, in save_base … -
How can I configure GeoNode 2.6 to PUBLIC IP?
I am new to GeoNode, I installed Geonode 2.6 on ubuntu 16 (http://docs.geonode.org/en/master/tutorials/install_and_admin/quick_install.html) and after successfully installed it, I configured my server to a public IP and using sudo geonode-updateip command I changed my ip in geonode, but after that I can't login to geonode application, Browser show "The connection was reset" (I thing its a time out) Checked with local ip, its working.And I changed Proxy Base URL on geoserver to public IP, still not solved. How can I fix this? Geoserver log last lines 2017-11-22 10:01:14,734 DEBUG [org.geoserver.security.filter.GeoServerSecurityContextPersistenceFilter$1] - SecurityContextHolder now cleared, as request processing completed 2017-11-22 10:01:15,036 DEBUG [org.geoserver.security.IncludeQueryStringAntPathRequestMatcher] - Checking match of request : 'Path: /web/, QueryString: null'; against '/web/**' 2017-11-22 10:01:15,036 DEBUG [org.geoserver.security.IncludeQueryStringAntPathRequestMatcher] - Matched Path: /web/, QueryString: null with /web/** 2017-11-22 10:01:15,042 TRACE [org.geoserver.ows.OWSHandlerMapping] - No handler mapping found for [/web/] 2017-11-22 10:01:15,043 TRACE [org.geoserver.ows.OWSHandlerMapping] - No handler mapping found for [/web/] 2017-11-22 10:01:15,043 TRACE [org.geoserver.ows.OWSHandlerMapping] - No handler mapping found for [/web/] 2017-11-22 10:01:15,043 TRACE [org.geoserver.ows.OWSHandlerMapping] - No handler mapping found for [/web/] 2017-11-22 10:01:15,185 DEBUG [org.geoserver.filters] - Creating a new http session inside the web UI (normal behavior) java.lang.Exception: Full stack trace for the session creation path at org.geoserver.filters.SessionDebugFilter$SessionDebugWrapper.getSession(SessionDebugFilter.java:92) at javax.servlet.http.HttpServletRequestWrapper.getSession(HttpServletRequestWrapper.java:229) at … -
Django installed but throws import error in virtual env when running: sudo python manage.py collectstatic
I am working in a virtual environment. When I run import django and django.VERISON, I get >>> django.VERSION (1, 10, 2, 'final', 0) but when I run the command sudo python manage.py collectstatic it throws error: "Couldn't import Django. Are you sure it's installed and " ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? I checked the sys.path inside virtual env and it does not have django. it has these: ['', '/www/XXX/venv/lib/python35.zip', '/www/XXX/venv/lib/python3.5', '/www/XXX/venv/lib/python3.5/plat-x86_64-linux-gnu', '/www/XXX/venv/lib/python3.5/lib-dynload', '/usr/lib/python3.5', '/usr/lib/python3.5/plat-x86_64-linux-gnu', '/www/XXX/venv/lib/python3.5/site-packages'] I still don't know how to make it work. Should I install django again in virtualenv, or should I uninstall the version already there on the server, or should I just add it to python variable? Also I if should do one of these things, how to do it? I am working with a server for the first time, hence not doing anything intuitively. -
Django Form Request.GET only get 1 value from multiple selected field
I have a multi select field using select2 in my form, i want to get all the value selected when submit, but when I print the value, its only get the value of the last selected option, how can i fix this? Any help is much appreciated, below is my code : html <select class="js-example-basic-multiple" name="Project" multiple="multiple" style="display:inline-block;"> <option value="ALL" checked="1">ALL</option> <option value="1">a</option> <option value="2">b</option> <option value="3">c</option> <option value="4">d</option> </select> <script> $('.js-example-basic-multiple').select2(); $('.js-example-basic-multiple').on('change', function() { var a = $('.js-example-basic-multiple').val(); }) </script> view.py if 'Project' in request.GET: print(request.GET['Project']) -
celery works not found if not start with sudo
I make use of celery with django, and setup supervisor according celery supervisor configuration example. but I found some error in log: unregister task. So, I test it on terminal by following CMD: celery worker -A dating -l INFO -P gevent Yes, not see my task. [tasks] . celery.accumulate . celery.backend_cleanup . celery.chain . celery.chord . celery.chord_unlock . celery.chunks . celery.group . celery.map . celery.starmap . dating.celery.debug_task After I swith to sudo like this: **sudo** celery worker -A dating -l INFO -P gevent the output show all my task. [tasks] . celery.accumulate . celery.backend_cleanup . celery.chain . celery.chord . celery.chord_unlock . celery.chunks . celery.group . celery.map . celery.starmap **. dater.tasks.xxx** . dating.celery.debug_task **. feed.tasks.xxx** I have no idea about this problem, please help to check it, Thanks. PS: i set user: www-data in /etc/supervisor/conf.d/celery.conf and checked the owner of log and python script, all are www-data. dating/celery.py: from __future__ import absolute_import import os from celery import Celery os.environ.get('C_FORCE_ROOT', True) os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'dating.settings') app = Celery('dating') app.conf.update( broker_url = 'redis://localhost:6379', result_backend = 'redis://localhost:6379', task_serializer='msgpack', result_serializer='json', accept_content=['msgpack', 'json'], # Ignore other content enable_utc=True, result_expires=3600*24, ) # Load task modules from all registered Django app configs. app.autodiscover_tasks() -
Django Rest Framework: An example how to post a new ordering of tracks
I am using Django Rest Framework and I have a situation similar to the Album and Tracks example used in the documentation here : http://www.django-rest-framework.org/api-guide/relations/#api-reference I want to make an endpoint that allows me to post this JSON data [{"id":1},{"id":2},{"id":3},{"id":4},{"id":6},{"id":7},{"id":8},{"id":9},{"id":10},{"id":11},{"id":12},{"id":13},{"id":75},{"id":76},{"id":77},{"id":78}] so that the Tracks will be reordered accordingly within the Album they belong to. The ids in the json data refer to the primary key of the tracks. The field I use to store their order is order and the unique index is unique_together = ('album', 'order') I can write my own custom endpoint to satisfy this, but was wondering if I can reuse whatever existing code that DRF already has to fulfil this. I have looked at https://github.com/miki725/django-rest-framework-bulk but I am using Django Rest 3.6.3 Django 1.10, python 3 so it appears to be outdated for me. -
Change "Quit the server with CTRL-BREAK."
Is there a way in one of the Django scripts to change the CTRL-BREAK exit command to something else when using "python manage.py runserver?" -
Map Mannually Created Table as M2M in Django
I have table T1 (list of all words Used in Text) and T2 (list of Text). I have created another Table T3 with foreign key to T1, and T2 so that it can act as M2M, in T3. I additionally add another column called WordCount, so i cannot create this table with models.ManyToMany Field! Can I access T2 from T1 using Many to many Constrains in Django ORM? -
Why I count’t use get_user_model() at import time
Just as the title, I cannot import usercreationform . The exception is model haven’t been loaded. It’s only appears in Django 1.10. There’s no such problem in Django 1.11 . I know it depends on whether get_user_model() can be called at runtime. What should I do to solve it in Django 1.10? -
What is the best way to restrict jsonField's key value in Django model
I working on Django project for that i need a model to keep personalized_information from user. This field is individual independent so i keep this as a jsonField. Now i am wondering what is the best possible way to restrict key values of this field. Say some user would like to share name, address, email to us and some just want to share name. This list can increase from time to time. So its very hard to predict what is going to be needed as future. For simplicity i like to keep this information as a json response in my database. What is the best design for this problem? -
Checking the existence of a permission object in Django unit test
Suppose that I want to write a test to make sure that a permission does not exist. I want the following test to pass (instead it gives an error): from django.test import TestCase from django.contrib.auth.models import Permission class TestPermission(TestCase): def test_existence_of_permission(self): self.assertIsNone(Permission.objects.get(codename='a_non_existant_permission')) This gives me the following error: django.contrib.auth.models.DoesNotExist: Permission matching query does not exist. How can I test the non-existence of this permission? -
Unique constraint on a pair of fields, bidirectional
Take this model for example class Relationship(models.Model): user1 = models.ForeignKey(User) user2 = models.ForeignKey(User) class Meta: unique_together('user1', 'user2') The unique_together constraint will only work in one direction. The same relationship can be represented in 2 different ways: user1 = Foo user2 = Bar AND user1 = Bar user2 = Foo Is it possible to use unique_together to enforce a bidirectional constraint at the database level? -
How correctly add permissions to User model of Django?
I am tring to add custom permissions to User model (django.contrib.auth.models). To __init__.py file of my users app I add: from django.db.models.signals import pre_migrate from django.contrib.contenttypes.models import ContentType from django.contrib.auth import models as auth_models from django.contrib.auth.models import Permission from django.conf import settings from django.dispatch import receiver @receiver(pre_migrate, sender=auth_models) def add_user_permissions(sender, **kwargs): content_type = ContentType.objects.get_for_model(settings.AUTH_USER_MODEL) Permission.objects.get_or_create(codename='view_user', name=' Can view users', content_type=content_type) Permission.objects.get_or_create(codename='change_user_password', name=' Can change user password', content_type=content_type) settings.py: INSTALLED_APPS = [ 'users', # "users" application ] ERROR: Traceback (most recent call last): File "/Users/nurzhan_nogerbek/Virtualenvs/py2714/lib/python2.7/site-packages/django/utils/autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "/Users/nurzhan_nogerbek/Virtualenvs/py2714/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 117, in inner_run autoreload.raise_last_exception() File "/Users/nurzhan_nogerbek/Virtualenvs/py2714/lib/python2.7/site-packages/django/utils/autoreload.py", line 251, in raise_last_exception six.reraise(*_exception) File "/Users/nurzhan_nogerbek/Virtualenvs/py2714/lib/python2.7/site-packages/django/utils/autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "/Users/nurzhan_nogerbek/Virtualenvs/py2714/lib/python2.7/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/nurzhan_nogerbek/Virtualenvs/py2714/lib/python2.7/site-packages/django/apps/registry.py", line 85, in populate app_config = AppConfig.create(entry) File "/Users/nurzhan_nogerbek/Virtualenvs/py2714/lib/python2.7/site-packages/django/apps/config.py", line 94, in create module = import_module(entry) File "/usr/local/Cellar/python/2.7.14/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/Applications/Projects/web/dashboard.kase.kz/users/__init__.py", line 5, in <module> from django.contrib.contenttypes.models import ContentType File "/Users/nurzhan_nogerbek/Virtualenvs/py2714/lib/python2.7/site-packages/django/contrib/contenttypes/models.py", line 139, in <module> class ContentType(models.Model): File "/Users/nurzhan_nogerbek/Virtualenvs/py2714/lib/python2.7/site-packages/django/db/models/base.py", line 110, in __new__ app_config = apps.get_containing_app_config(module) File "/Users/nurzhan_nogerbek/Virtualenvs/py2714/lib/python2.7/site-packages/django/apps/registry.py", line 247, in get_containing_app_config self.check_apps_ready() File "/Users/nurzhan_nogerbek/Virtualenvs/py2714/lib/python2.7/site-packages/django/apps/registry.py", line 125, in check_apps_ready raise AppRegistryNotReady("Apps aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. Question: How to fix this error? -
CSS + Django - Displaying list of items with grid?
I am trying to display a list of questions (think Stack Overflow's question list), and using grid to display them. I want to display all the questions in the content section and have a separate sidebar section for other stuff. The web page will basically look like this; A=content, B1=sidebar. The thing is, I can't figure out how I can repeat a list of questions in the content section without also repeating content in the sidebar section. My content section is itself a grid. What should I do? This doesn't work, because the content class repeats <div class="body"> {% for question in questions %} <div class="content"> <div class="content1"> ... content here </div> <div class="content2"> ... content here </div> </div> {% endfor %} <div class="sidebar"> ... content here </div> </div> This works, but it is not optimal because the sidebar section repeats as well {% for question in questions %} <div class="body"> <div class="content"> <div class="content1"> ... content here </div> <div class="content2"> ... content here </div> </div> <div class="sidebar"> ... content here </div> </div> {% endfor %} CSS .body { display: grid; grid-template-columns: 3fr 1fr; } .content { display: grid; grid-template-columns: 40px 500px 200px; } -
Append filename and line to Django queries as SQL comment
I'm interested in using this as a profiling technique - I have various ways of observing queries in my DB (slow query logs, etc.) which don't integrate with Python stacktraces (as you'd get with Django Debug Toolbar or similar tools). The idea is that if I were to look at queries in my DB, I would see e.g. SELECT foo FROM bar # my_django_model.py:132 and I'd be able to look at my_django_model.py and see the line that the Django queryset execution came from. Has anyone already figured out a good way to accomplish this? -
Plot result of SVM in Django wep app
I'm working with sklearn.svm to handle the Support vector machine (SVM). And most examples used pylab or matplotlib to plot the result. Please give me an example how I can plot the result of SVM in django web app. Something like this: