Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is there any way to run unittest from button click on django sites?
I have written unit tests as well the django documentation. I can run tests from python manage.py test. That's good. But, I want to run test from a button click. This button can be anywhere in my UI. Also I want to generate a simple report on passed or failed. Is it possible with Python/Django unittest module? -
How would you make an Excel-like user interface with Django?
I am currently working on a project where the user wants the user interface to look like an Excel document. This is because the user normally writes data into an Excel document, and wants to switch to writing data straight into the user-interface instead. It should look something like this: In this project, so far, I have only used Django, and there was no need for using Bootstrap, for example. However, I would be willing to use a front-end framework in order to create this Exel-like user interface. Trying to make html-tables have been unsuccessful so far. Does anyone have suggestions on how it might be done? Thank you! -
Convert datetime to local time from Django Query to Openpyxl
Django converts the date time (I use timezone.now() to store in database) to local time in templates fine. What I need help on is when it is written to a cell in openpyxl. Right now, I simply assign the attribute of the query to the cell. query = SomeModel.objects.latest() date_recorded = query.date_recorded In templates, date_recorded is already converted to local time. No problem there. ws.cell(row=rows, column=cols).value = date_recorded The above code results to UTC. Please help me convert it to local time. Thank you. -
Linear Scale Django form widget
I am looking for some guidance in order to create a widget that is not documented at all in the django documentation but is an evident part of forms. And I am talking about Linear Scales widgets for forms. Giving the ability to a user to choose on a scale between 1-100 a score If you have any idea on how to do it, any direction I would be please to get it ;) thx you very much -
Not able to access server when invoking gunicorn via .bash file
I am not able to access server when starting gunicorn via a .bash file I made. It works when I do it manually with this command $ gunicorn project.wsgi:application --bind 192.168.1.130:8000 Created a gunicorn.bash file from tutorials. I looks like this and runs without fault. #!/bin/bash NAME="project" # Name of the application DJANGODIR=/home/username/projects/project # Django project directory SOCKFILE=/home/username/.venvs/project/run/gunicorn.sock # We will communicate using this unix socket USER=username # the user to run as GROUP=username # the group to run as NUM_WORKERS=1 # how many worker processes shoul Gunicorn spawn DJANGO_SETTINGS_MODULE=project.settings.production # which settings file should Django use DJANGO_WSGI_MODULE=project.wsgi # WSGI module name echo "Starting $NAME as `whoami`" # Activate the virtual environment cd $DJANGODIR source /home/username/.venvs/project/bin/activate export DJANGO_SETTINGS_MODULE=$DJANGO_SETTINGS_MODULE export PYTHONPATH=$DJANGODIR:$PYTHONPATH # Create the run directory if it doesn't exsist RUNDIR=$(dirname $SOCKFILE) test -d $RUNDIR || mkdir -p $RUNDIR # Start yout Django Unicorn # Programs meant to be run under supervisor should not daemonize themselves (do not use daemon) exec gunicorn ${DJANGO_WSGI_UNICORN}:application \ --name $NAME \ --workers $NUM_WORKERS \ --user=$USER --group=$GROUP \ --bind=unix:$SOCKFILE \ --log-level=debug \ --log-file=- I don't know how to troubleshoot this? Maybe some command to see what differs in running settings from manually starting gunicorn and from … -
Getting status of task from Django Background Tasks
I am working with Django and i want to start some background tasks. I found the library "Django Background Tasks". It has almost everything I need but I can not find how to get the status of the task (pending/running/completed) anywhere in the documentation (http://django-background-tasks.readthedocs.io/en/latest/). It would be cery helpful for me if someone could tell me how to get the status of the task. -
facebook app can not find my localserver redirected url
I working on third party social login facebook by using django-social-authpackage. But when try to login bellow error show . I also use django-allauth package and for that i use answerme facebook app.But same problem shown there also. -
Django web app: how to save thousands of variables per user
There is a website driven by Django where the user logs in and can answer thousands of questions. I want to persistently save whether a given user has answered a given question or not. My approach so far is for the User table to have thousands of columns in the PostgreSQL database - a column for each question. I read there is a 1,600 column limit in PostgreSQL, which I haven't reached yet, but would reach eventually. What is a viable architecture for this kind of functionality in a web app? -
Django database error when running tests
I have been trying to solve a database related error for a long time which prevents me from running tests unless I disable migrations temporarily before launching the task. I am getting a ProgrammingError, specifically: django.db.utils.ProgrammingError: relation "django_facebook_open_graph_share" does not exist LINE 1: ...ango_facebook_open_graph_share"."created_at" FROM "django_fa... when running test someapp --verbosity=2. This is the displayed output: Creating test database for alias 'default' ('test_dbname')... Type 'yes' if you would like to try deleting the test database 'test_dbname', or 'no' to cancel: Got an error creating the test database: database "test_dbname" already exists yes Destroying old test database 'default'... Operations to perform: Synchronize unmigrated apps: app1, app2, app3 Apply all migrations: appx, appy, appz Synchronizing apps without migrations: Creating tables... Running deferred SQL... Installing custom SQL... Running migrations: Rendering model states... DONE Applying app1.0001_initial... OK ...many more lines line the one above... Applying appn.000x_someapp... OK Traceback (most recent call last): ..trace... django.db.utils.ProgrammingError: relation "django_facebook_open_graph_share" does not exist LINE 1: ...ango_facebook_open_graph_share"."created_at" FROM "django_fa... I am having trouble figuring out what migration is causing that error because the log doesn't point it out. I assume it is the one being executed right after appn.000x_someapp but it just doesn't say which one it is, so … -
How to allow access only for kubernetes pods in postgresql?
I have a Django app running in Kubernetes in GKE. And that django app connects to a static (non-containerized) postgresql server. As both of them are located in one zone, my django app uses internal IP to connect to database. I want only my django app to request a connection to the postgresql database and deny connection for requests coming from other IPs. To do that, in pg_hba.conf I did this: host all all 14.133.0.0/24 md5 Because all internal IPs start with 14.133. However, the requests are coming from pod IPs and thus requests for connection are denied. An example for a Pod IP can be 14.4.123.32. So, if I do the following in pg_hba.conf, the problem will be fixed: host all all 14.0.0.0/8 md5 Another thing to note is that Pod IPs always change. So, this solution will break once the pod is updated. What is the best practice to go about this? -
Test asc for arg which is self
Test should give 400 status code, but it ascs for self as argument, but isn't it a mistake? This is test: def test_cab_number_does_not_exist(self): data = {"cab_number": "0"} self.client = self.Client url = reverse('api:orders') response = self.client.post(url, data) response_content = json.loads(response.content) cab_number = response_content['cab_number'] self.assertEqual(response.status_code, 400) This function gives mistake like: TypeError: test_cab_number_does_not_exist() takes exactly 1 argument (0 given) . I don't know how to fix it. -
Celery is constantly starting with supervisor
How to run celery in Supervisor? This is my .conf file: [program:celery_worker] command=celery -A urlextractor worker -l info process_name=%(program_name)s ; process_name expr numprocs=1 directory=/home/omuntean/Django/urlextractor /urlextractor ; directory to cwd to before exec (def no cwd) autostart=true ; start at supervisord start (default: true) autorestart=unexpected ; when to restart if exited after running user=root stopasgroup=true stopsignal=QUIT stdout_logfile=/var/log/urlextractor /celery_w_out.log stderr_logfile=/var/log/urlextractor /celery_w_err.log priority=100 If I run the celery command normally it works fine without any errors, however, when I type: sudo service supervisor start Then see the status with: supervisorctl status It gives me: celery_worker RUNNING pid 10651, uptime 0:00:02 urlextractor RUNNING pid 9761, uptime 0:08:08 And then after I type again it gives me: celery_worker STARTING urlextractor RUNNING pid 9761, uptime 0:08:09 Why is this happening and how can I make it work? -
Organizing a one-to-one relationships for checksums
Django==1.11.6 I'd like to collect checksums for uploaded files. I have done it via GenericRelation. This is clumsy. Because it is one-to-many relationship whereas a checksum is definitely one-to-one. Could you help me understand whether this can be rewritten as a one-to-one relationship case? @receiver(post_save, sender=ItemFile) @receiver(post_save, sender=Image) def save_file_checksum(sender, instance, **kwargs): """ Save a ckecksum for a file. """ checksum = get_checksum(instance.file.path) existing_checksum = instance.checksum.first() if existing_checksum: existing_checksum.checksum = checksum existing_checksum.save() else: FileChecksum.objects.create(content_object=instance, checksum=checksum) class ItemFile(models.Model): file = models.FileField(blank=False, max_length=255, upload_to=get_item_path, verbose_name=_("file")) checksum = GenericRelation(FileChecksum) class Image(models.Model): file = models.ImageField(blank=False, verbose_name=_("Image"), max_length=255, upload_to=get_sheet_path) checksum = GenericRelation(FileChecksum) class FileChecksum(models.Model): content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') checksum = models.CharField(blank=True, null=False, max_length=255, verbose_name=_("checksum")) def __str__(self): return "{} {}: {}".format(self.content_type, self.content_object, self.checksum) -
Running multiple instances of daphne behind a load balancer: django-channels
I am using django-channels to add HTTP2 & WebSocket support for my application. I could not find a lot of documentation as to how to scale channels. Below is my nginx configuration that load balances multiple instances of daphne running on the same machine but different ports. Is this the correct way to do it? upstream socket { least_conn; server 127.0.0.1:9000; server 127.0.0.1:9001; server 127.0.0.1:9002; server 127.0.0.1:9003; } server { listen 80; server_name 127.0.0.1; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/niscp/home-screen; } location /nicons/ { root /home/niscp/home-screen; } location / { include uwsgi_params; uwsgi_pass unix:/home/niscp/home-screen/home-screen.sock; } location /ws/ { proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_pass http://socket; } } Along with that, I am running individual instances of workers to listen to individual channels in the following manner: python manage.py runworker --only-channels=websocket.connect python manage.py runworker --only-channels=websocket.receive python manage.py runworker --only-channels=websocket.disconnect I have got uwsgi to handle all http requests the way django normally handles them. All daphne and workers do is handle WebSocket requests. Is this a viable method to scale django-channels, or is there something I could do better? -
'Authorization: Bearer token' vs 'Authorization: token' (Can't use Bearer header in Oauth2)
I'm using Oauth2. And somehow I can't attach Bearer header. It only work without Bearer Header. (But header Token header works) Is there any advantage of using Bearer? Should I use it? def get_queryset(self): # signing self.request.user header_token = self.request.META.get('HTTP_AUTHORIZATION', None) if header_token is not None: try: token = sub('Token ', '', self.request.META.get('HTTP_AUTHORIZATION', None)) token_obj = Token.objects.get(key = token) self.request.user = token_obj.user except Token.DoesNotExist: pass qs = Outfit.objects.all(user=self.request.user) return qs Can I do this with Bearer header? -
Leverage Browser caching django-nginx not working
I prepare a django project with server engine nginx using gunicorn for that. I am trying to work out page insights and I want to leverage browser caching in my nginx settings. My directory layout of project is: mainprojectfolder --mainproject ----static manage.py --media_cdn --static_cdn In my settings.py I arranged static files : STATIC_URL = '/static/' MEDIA_URL = '/media/' STATIC_ROOT = "/home/ytsejam/public_html/ozkansimple/static_cdn/" MEDIA_ROOT = "/home/ytsejam/public_html/ozkansimple/media_cdn/" My nginx settings are server { listen 80; server_name www.ozkandurakoglu.com; client_max_body_size 4G; root /home/ytsejam/public_html/ozkansimple/; access_log /home/ytsejam/public_html/ozkansimple/logs/nginx-access.log; location /static/ { autoindex on; alias /home/ytsejam/public_html/ozkansimple/ozkand/static/; } location /media/ { autoindex on; alias /home/ytsejam/public_html/ozkansimple/media_cdn/; expires 365d; } #location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ { # expires 365d; # } } when I comment out cache , all my static and media files gets 404 and nothing is shown. can you help me ? Thanks -
Replacing image dynamically using jQuery
I'm trying implement a like button that changes color when clicked. I am trying to replace the image dynamically using jQuery. <div class = "col-sm-10" style = "margin-top: 2%"> <input style = "width : 4%; height: 4%" type = "image" id = {{schedule.id}} + "image" class = "likes" data-scheduleid = "{{schedule.id}}" data-user = "{{curruser.person.id}}" src = "{% static 'img/notliked2.png' %}"/> </div> This is image file that gets pressed as a button. Essentially, I am trying to change the image file on click. $(document).ready(function() { $('.likes').click(function(e){ var sched_id; var curruser; sched_id = $(this).attr("data-scheduleid"); curruser_id = $(this).attr("data-user"); $.get('/profiles/like_schedule/', {schedule_id: sched_id, current_user: curruser_id}, function(data){ var first = data.split("/") $('#' + sched_id).html(first[0]); console.log(first[1]) //$('#likes').html("<input style = 'width : 4%; height: 4%' type = 'image' id = {{schedule.id}} class = 'likes' data-scheduleid = '{{schedule.id}}' data-user = '{{curruser.person.id}}' src = {% static 'img/" + first[1] + "' %}/>"); $('.' + sched_id + "image").attr("src", "{% static 'img/" + first[1] + "' %}") e.preventDefault(); }); }); }); This is the jQuery. I logged first[1], and it is correct. It alternates between "notliked2.png" and "liked2.png" when someone likes and unlikes. But for some reason replacing the image source doesn't work. I even tried replacing the entire html, and it … -
Get the IP of the response hit by the requests library and even make it a bit faster in Django Python2.7
I am creating a django application where I have to scrape my profile for displaying purpose. The following is the views.py: url = 'my public profile' header = {'User-Agent': "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) " "Chrome/43.0.2357.134 Safari/537.36"} extract_profile = requests.get(url, headers=header) Here I have a guess that the scraping what I am trying is done through my server IP. I am not getting the idea to how I can make use of my my local IP for scraping the profile instead of my server IP? Also this process is taking a hell lot of time which is not good or my experiment. So I want to know what I need to improve to make it faster? kindly, let me know so I improve. -
https redirect custom domain google app engine
I have a custom domain in google app engine. I have all ok. Capture But when It do the redirection, it redirect to http domain, not https domain. If change the domain manually to https, it work. The domain is in google domain. -
Python-Neo4j Security error while connecting to database Failed to establish secure connection to '[SSL:UNKNOWN_PROTCOL(_ssl.c:600)
Im trying to connect the Django to Neo4j using neo4j-driver but I'm getting Security error. Error is :- neo4j.exceptions.SecurityError: Failed to establish secure connection to '[SSL: UNKNOWN_PROTOCOL] unknown protocol (_ssl.c:600)' Python Version 3.4.3 My Dependencies django1.9 neo4j-driver==1.4.0 CODE Views.py from django.shortcuts import render # Create your views here. from neo4j.v1 import GraphDatabase,basic_auth from django.conf import settings from django.db import IntegrityError from django.views.decorators.cache import cache_page from django.http import HttpResponse from django.contrib import messages from django.http import HttpResponse, HttpResponseRedirect, JsonResponse,Http404 from django.http import StreamingHttpResponse from django.shortcuts import render_to_response from django.shortcuts import render from django.template import RequestContext from django.views.decorators.csrf import csrf_exempt from django import template uri = "bolt://localhost:7474" driver = GraphDatabase.driver(uri, auth=("neo4j", "aditya369")) def friends(request): name = "Cameron Crowe" with driver.session() as session: with session.begin_transaction() as tx: for record in tx.run("MATCH (a:Person)-[:PRODUCED]->(f) " "WHERE a.name = {name} " "RETURN f.title", name=name): print(record["f.title"]) return render(request, "friends.html") Error The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/Users/sskadit/Desktop/graphdb/src/lib/python3.4/site-packages/django/utils/autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "/Users/sskadit/Desktop/graphdb/src/lib/python3.4/site-packages/django/core/management/commands/runserver.py", line 116, in inner_run self.check(display_num_errors=True) File "/Users/sskadit/Desktop/graphdb/src/lib/python3.4/site-packages/django/core/management/base.py", line 426, in check include_deployment_checks=include_deployment_checks, File "/Users/sskadit/Desktop/graphdb/src/lib/python3.4/site-packages/django/core/checks/registry.py", line 75, in run_checks new_errors = check(app_configs=app_configs) File "/Users/sskadit/Desktop/graphdb/src/lib/python3.4/site-packages/django/core/checks/urls.py", line 10, in check_url_config return check_resolver(resolver) File "/Users/sskadit/Desktop/graphdb/src/lib/python3.4/site-packages/django/core/checks/urls.py", … -
Changed JWT to OAuth2 and getting "Invalid token header. No credentials provided."
I decided to change my HTTP Authorization method from JWT to OAuth2. While testing my API with Postman, I'm getting same error for hours, "Invalid token header. No credentials provided." My header is Authorization: Bearer 416a444281fdcd6d2a344970eea0d47c22d01528 I don't see anything wrong in settings.py, but Do you see any? I commented out JWT setting just in case. INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'corsheaders', 'allauth', 'allauth.account', 'rest_auth.registration', 'rest_framework', 'rest_framework.authtoken', 'oauth2_provider', 'social_django', 'rest_framework_social_oauth2', 'rest_auth', ... 'allauth.socialaccount', 'storages', 'allauth.socialaccount.providers.facebook', ... ] # localhost:8000/ SITE_ID = 7 ACCOUNT_AUTHENTICATION_METHOD = 'username_email' ACCOUNT_EMAIL_VERIFICATION = 'none' SOCIALACCOUNT_EMAIL_VERIFICATION = 'none' REST_USE_JWT = False # for gmail EMAIL_USE_TLS = True EMAIL_HOST = ... EMAIL_HOST_USER = .. EMAIL_PORT = ... EMAIL_HOST_PASSWORD = ... EMAIL_BACKEND = ... DEFAULT_FROM_EMAIL = ... SERVER_EMAIL = ... LOGOUT_ON_PASSWORD_CHANGE = False OLD_PASSWORD_FIELD_ENABLED = True AUTHENTICATION_BACKENDS = ( # Oauth2 backends 'oauth2_provider.backends.OAuth2Backend', # Needed to login by username in Django admin, regardless of `allauth` 'django.contrib.auth.backends.ModelBackend', # `allauth` specific authentication methods, such as login by e-mail 'allauth.account.auth_backends.AuthenticationBackend', # Facebook OAuth2 'social_core.backends.facebook.FacebookAppOAuth2', 'social_core.backends.facebook.FacebookOAuth2', # django-rest-framework-social-oauth2 'rest_framework_social_oauth2.backends.DjangoOAuth2', ) MIDDLEWARE = [ # OAuth2 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'oauth2_provider.middleware.OAuth2TokenMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] CORS_ORIGIN_WHITELIST = ( '10.0.2.2', 'localhost' ) ROOT_URLCONF = ... TEMPLATES = [ … -
Django QuerySet/Manager filter employees by age from birthday
I am a beginner. I would like to get list employees have age > 25 and calculate the average age of employees. Currently, we need to get age from birthday (I have no idea about it ^^) . Please help me create sample QuerySet/Manager about it. Thanks all :)) My model: class Employee(models.Model): """"Employee model""" first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) birthday = models.DateField(max_length=8) -
Django model manager transaction and signal
# The model class UserManager(models.Manager): def create_user(self, temp_user_id): new_user = self.create(require data) # insert row to model B # The model manager class User(models.Model): # model fields objects = UserManager() # Post save signal handler def send_notification_to_user(sender, instance, created, **kwargs): # send sms notification to the newly created user signals.post_save.connect(send_notification_to_user, sender=User) # The view class UserView(APIView): def post(self, request, format=None): try: with transaction.atomic(): c_user = User.objects.create_user(request.data["temp_reg_id"]) return Response(status=status.HTTP_201_CREATED) except Exception as e: return Response(status=status.HTTP_400_BAD_REQUEST) In this scenario if a user registered then user get a sms. But here I'm running the model manager in transaction, so if somehow # insert row to model B instruction fails then all database will rollback. The problem is in this situation user will get the account creation sms, which is not true. How can I overcome this problem or which approach will be better? My English is not good, you can ask me for more explanation. -
django use spyne lib on apache server response no content
I have develop a webservice ,use spyne.protocol.soap.soap11. when running In django command (python manage runserver), it works as expected: 1.I can get wsdl file from $url?wsdl 2.call a webservice and get response but when deployed in apache server, it response $url?wsdl with status 200 OK but no content: "Connection →close Content-Length →0 Content-Type →text/xml; charset=utf-8 Date →Mon, 16 Oct 2017 02:22:08 GMT Server →Apache/2.2.15 (CentOS)" and I can also call a webservice, and the server do what i want(insert a data to database) but apache server response no content. note:all above running in the same machine, same python I have search in google and stackoverflow, but there is no similar questions. -
Django/AngularJS: How do I access my Python Context Items from my AngularJS Script
Good day SO! I am a beginner thats trying out a Django Project while using AngularJS for my frontend Firebase chat system. Here is a previous question that I asked regarding this project: Firebase/Angular: Messages not showing in HTML, but contain the message objects I know that it is not wise to use json variables on your html directly while using django/python, but it just so happens that my firebase chat module is using angularJS (and I do not know how to code this chat function in django..), and my angularJS code requires access to my Django's context querysets from View.py. Is there any way that I can either: Push json items into my HTML/Template the same way I push context information into my HTML/Template from Views.py and use it in my AngularJS Script? Access my Django/Python's data sets from Context from Views.py? Here is my AngularJS code for firebase: var app = angular.module('chatApp', ['firebase']); app.controller('ChatController', function($scope, $firebaseArray) { //I want to populate the crisis and sender variables with something from my context //from Views.py.. var crisis = "Crisis1"; var sender = "Sender1"; //Query var ref = firebase.database().ref().child(crisis).child('CMO-PMO'); $scope.messages = $firebaseArray(ref); $scope.send = function() { $scope.messages.$add({ sender: sender, message: $scope.messageText, …