Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Sorting a table by clicking the table head column in Django Web
So I have a website in django. I have a table with a few colums like ServerName,IP etc.. I would like to have the header of the columns to sort the entire column. For example when I click the ServerName column it will order all the items by ABC order of the ServerName. I have heard of django-sorting-bootstrap but the guide seem complicated. Is there any easier or good guide to do that? the idea is to click with the arrow on the head and it will sort it out (It will be like a link). index.html table- <div class="container"> <br> <center><h1>DevOps Server List</h1></center> <br> <form method='GET' action=''> <input type='text' name='q' placeholder='Search Item'/> <input type='submit' value='Search' /> </form> <table class="table table-hover"> <thead> <tr> <th> Server Name </th> <th> Owner </th> <th> Project </th> <th> Description </th> <th> IP Address </th> <th> ILO </th> <th> Rack </th> <th> Status </th> <th> </th> </tr> </thead> <tbody> {% for server in posts %} <tr> <div class ="server"> <td>{{ server.ServerName }}</td> <td>{{ server.Owner }}</td> <td>{{ server.Project }}</td> <td>{{ server.Description }}</td> <td>{{ server.IP }}</td> <td>{{ server.ILO }}</td> <td>{{ server.Rack }}</td> <td>{{ server.Status }}</td> <td> <button type="button" class="btn btn-primary" data-toggle="modal" href="#delete-server-{{server.id}}" data-target="#Del{{server.id}}">Delete <span class="glyphicon glyphicon-trash" </span></button> … -
Why Django serialize returns string
I have problem with returning something browsable form serializers.serialize. My model: class BowlingGame(models.Model): Frame = models.PositiveSmallIntegerField() FrameRow = models.PositiveSmallIntegerField() Result = models.PositiveSmallIntegerField(blank=True, null=True) StrikeSpare = models.PositiveSmallIntegerField(blank=True, null=True) StrikeSpareInfo = models.CharField(max_length=1, blank=True, null=True) Time = models.DateTimeField(blank=True, null=True) GameId = models.PositiveIntegerField() StateOfGame = models.PositiveSmallIntegerField(default=1) class Meta: ordering = ('GameId',) def __str__(self): return str(self.GameId) And what I do next: >>> from django.core import serializers >>> from django.db.models import Max >>> from game.models import BowlingGame >>> a = BowlingGame.objects.all().aggregate(Max('GameId'))['GameId__max'] >>> game_frame = BowlingGame.objects.filter(GameId=a) >>> me = serializers.serialize('json', game_frame, fields=('Frame', 'FrameRow')) >>> me '[{"model": "game.bowlinggame", "pk": 2356, "fields": {"Frame": 1, "FrameRow": 1}}, {"model": "game.bowlinggame", "pk": 2357,......}}]' This seems to be string as >>> me[0] '[' and I'm looking for the first element of the queryset. I tried few more things: >>> me = serializers.serialize('json', [game_frame, ], fields=('Frame', 'FrameRow')) AttributeError: 'QuerySet' object has no attribute '_meta' My question: is it normal to return string? How I can browse the object. In fact I'm using it with AJAX but its the same. json.game_frame[0] returns '['. I need to be able to get the elements separately as normal dict or list. What is going on? -
How to add an option to view all (*) in Django?
I have a simple database with tables: Company 'CompanyID', 'int(10) unsigned', 'NO', 'PRI', NULL, 'auto_increment' 'CompanyName', 'varchar(70)', 'NO', '', NULL, '' 'Type', 'enum(\'C\',\'M\',\'S\',\'A\')', 'NO', 'MUL', NULL, '' 'Country', 'varchar(60)', 'YES', 'MUL', NULL, '' 'Website', 'varchar(60)', 'YES', '', NULL, '' 'Email', 'varchar(60)', 'YES', '', NULL, '' 'Telephone', 'double unsigned', 'YES', '', NULL, '' 'Maps_Link', 'varchar(60)', 'YES', '', NULL, '' CompanyDetails 'CompanyDetailsID', 'int(10) unsigned', 'NO', 'PRI', NULL, 'auto_increment' 'CompanyID', 'int(10) unsigned', 'NO', 'MUL', NULL, '' 'Type', 'enum(\'C\',\'M\',\'A\',\'S\')', 'NO', '', NULL, '' 'Category', 'enum(\'MEP Consultant\',\'Lighting Designer\',\'Architect\',\'Interior Designer\',\'MEP Contractor\',\'Fitout Contractor\',\'Procurement Company\',\'Developer\',\'Outdoor-Architectural\',\'Indoor-Architectural\',\'Indoor-Decorative\',\'Outdoor-Decorative\',\'Lamps\',\'Drivers\',\'Control Systems\',\'Landscaping Consultant\',\'Landscaping Contractor\',\'Other\')', 'NO', '', NULL, '' 'Comments', 'blob', 'YES', '', NULL, '' and 3 more tables (Contact, Continent, Product) I have created an app CompanyBrowser. I am trying to make a simple form with drop-down menus for: Type (from Company) Category (from Company Details) Country (from Company) For each of these, I want the user to have the option to select all (*) in the drop-down menu. Here is my urls.py: urlpatterns=[url(r'^$',views.Index,name='index'), url(r'^(?P<company_type>[CMSA*])/$',views.ResultsView.as_view(), name='results'), url(r'^(?P<company_type>[CMSA*])/(?P\<company_category>\w+)/$',views.ResultsView.as_view(), name='results'), url(r'^(?P<company_type>[CMSA*])/(?P<company_category>\w+)/(?P<company_country>\w+)/$',views.ResultsView.as_view(), name='results'), ]<br> Basically, I will be displaying according to url CompanyBrowser/company_type/company_category/company_country , where user can enter * i.e., all for any of the search field. This is the ResultsView I have coded so far: class … -
django admin edit model select/prefetch_related?
I have a Django website, with model Event, lets say: class Event(models.Model): home = models.ForeignKey('Team', related_name='%(class)s_home') away = models.ForeignKey('Team', related_name='%(class)s_away') ... class Team(models.Model): name = models.CharField("team's name", max_length=100) Using ForeignKeys for this was a bad idea, but anyway, how to make this usable in Django Admin page? In admin edit event page, a ton of foreign keys is fetched for this: http://127.0.0.1:8000/admin/event/event/116255/ It produces tons of selects like: SELECT "event_team"."id", "event_team"."name" FROM "event_team" WHERE "event_team"."id" = 346; and page dies. I was playing with these: class EventAdmin(admin.ModelAdmin): list_display = ('id', 'home', 'away', 'date_game', 'sport', 'result') search_fields = ['home__name', 'away__name'] list_select_related = ( 'home', 'away', 'league', 'sport', ... ) def get_queryset(self, request): return super(EventAdmin, self).get_queryset(request).select_related(*self.list_select_related) admin.site.register(Event, EventAdmin) But no luck. -
I want to use basic python modules for my django based website's back-end logic [on hold]
I want to use some of python's modules (especially audio and video modules) in my django based site's back-end processing. Is there any way to do it? Thanks -
How to send back the tokens to android using Firebase Auth
I am developing an Android app which uses Firebase and my own server running Django. What I intend to do is, I want to first authenticate the user using android app to the django server which then generates the custom tokens as specified in firebase docs. Then I want to send the generated custom token back to the android. My question is how to send that custom token back to android? I tried to send as JSON object. But it says JWT are not JSON serializable. I passed the username and password from android app as json object and authenticated with my django server. Here is my minimal Django code: import firebase_admin from firebase_admin import credentials from firebase_admin import auth cred = credentials.Certificate("firebase-admin.json") default_app = firebase_admin.initialize_app(cred) def validateuser(request): json_data=json.loads(request.body.decode('utf-8')) try: // I verify the username and password and extract the uid uid = 'some-uid' custom_token = auth.create_custom_token(uid) result={'TAG_SUCCESS': 1, 'CUSTOM_TOKEN': custom_token } except: result={'TAG_SUCCESS': 0, 'CUSTOM_TOKEN': '0'} return HttpResponse(json.dumps(result), content_type='application/json') But it says the custom token is not JSON serializable. Is it not the way to do like this? How do I send the custom token back to the android app? And this is the error: uid: 78b30d23-6238-4634-b2e4-73cc1f0f7486 custom_token: b'eyJraWQiOiAiZmFlNzA2MzZiY2UwZTk0Y2Y5YTM2OWRlNzc4ZDZlYWQ5NGMwM2MzYiIsICJhbGciOiAiUlMyNTYiLCAidHlwIjogIkpXVCJ9.eyJpc3MiOiAiZmlyZWJhc2UtYWRtaW5zZGstOXBtbjVAYnVzdHJhY2tlci0xZDE3OS5pYW0uZ3NlcnZpY2VhY2NvdW50LmNvbSIsICJ1aWQiOiAiNzhiMzBkMjMtNjIzOC00NjM0LWIyZTQtNzNjYzFmMGY3NDg2IiwgImF1ZCI6ICJodHRwczovL2lkZW50aXR5dG9vbGtpdC5nb29nbGVhcGlzLmNvbS9nb29nbGUuaWRlbnRpdHkuaWRlbnRpdHl0b29sa2l0LnYxLklkZW50aXR5VG9vbGtpdCIsICJleHAiOiAxNTA4MDc2OTA4LCAiaWF0IjogMTUwODA3MzMwOCwgInN1YiI6ICJmaXJlYmFzZS1hZG1pbnNkay05cG1uNUBidXN0cmFja2VyLTFkMTc5LmlhbS5nc2VydmljZWFjY291bnQuY29tIn0=.jgexW_xR5FeZvuO5TPWO8EOBnRJ28ut9OR_OxeajE1_o4ns4fwd2pMXlK2GkM464P5Vi-IxheG-IIJcANxGSDeZgvgpkLfKkHMZeSaraqfEQGq6N7ipuD8o1T7zd5qm79twmFbrQZRB1y7g1-zcjL69x8KFsThWOTmo0TYj5l3zf8_2Cxbw2SGefMWkCwL0d1yQjcUqVyuSAP3-Sg8KrrqCcG4cjNOXKeWxwbUQO7DobOQlT5TfRApwWk8Td6uPjD7d6jqMo-HPKOis0vRoXMBzflZKj36-hIOFkygZNbDWLTsQzbb3HZg8dBabA5GTy--iQi038TRMIm2W0irr0ng==' … -
django - TemplateDoesNotExist error
I am working through this Getting started with Django Rest Framework by Building a Simple Product Inventory Manager tutorial. At the end the tutorial, it says that I "should now be able to run your server and start playing with diffrent API endpoints". However, when I run the server, all I'm getting is a TemplateDoesNotExist error. At no point in the tutorial does it mention creating templates (and this is eventually going to connect to an Angular 2 frontend, as shown in this tutorial), so I'm confused at to whether this is an error in my code, or if the tutorial left a step out. I do not get any console errors when I run my code. serializers.py from .models import Product, Family, Location, Transaction from rest_framework import serializers class LocationSerializer(serializers.ModelSerializer): class Meta: model = Location fields = ('reference', 'title', 'description') class FamilySerializer(serializers.ModelSerializer): class Meta: model = Family fields = ('reference', 'title', 'description', 'unit', 'minQuantity') class ProductSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Product fields = ('sku', 'barcode', 'title', 'description', 'location', 'family') depth = 1 class TransactionSerializer(serializers.ModelSerializer): product = ProductSerializer() class Meta: model = Transaction fields = ('sku', 'barcode', 'product') views.py from __future__ import unicode_literals from django.shortcuts import render from rest_framework import … -
How to set own icon fonts using ALDRYN_BOOTSTRAP3_ICONSETS in django-cms
How to set own icon fonts using ALDRYN_BOOTSTRAP3_ICONSETS in django-cms? We can read on https://github.com/aldryn/aldryn-bootstrap3 that it should be something like this: ALDRYN_BOOTSTRAP3_ICONSETS = [ ('glyphicons', 'glyphicons', 'Glyphicons'), ('fontawesome', 'fa', 'Font Awesome'), # custom iconsets have to be JSON ('{"iconClass": "icon", "iconClassFix": "icon-", "icons": [...]}', 'icon', 'Custom Font Icons'), ('{"svg": true, "spritePath": "sprites/icons.svg", "iconClass": "icon", "iconClassFix": "icon-", "icons": [...]}', 'icon', 'Custom SVG Icons'), ] but I dont know how to configure new iconset in my case icons from http://rhythm.nikadevs.com/content/icons-et-line Could someone help me with that? -
nginx.service: Failed to read PID from file /run/nginx.pid: Invalid argument ubuntu 16.04 xenial
I know this is a known bug, but i dont know how to resolve that because i do lot of googling and after that finally back to stack to get some real solution : Here are configuration: First i install nginx by: sudo apt-get install nginx lsb_release -rd Description: Ubuntu 16.04.2 LTS Release: 16.04 apt-cache policy nginx-core nginx-core: Installed: 1.10.3-0ubuntu0.16.04.2 Candidate: 1.10.3-0ubuntu0.16.04.2 Version table: *** 1.10.3-0ubuntu0.16.04.2 500 500 http://sg.mirrors.cloud.aliyuncs.com/ubuntu xenial-updates/main amd64 Packages 500 http://sg.mirrors.cloud.aliyuncs.com/ubuntu xenial-security/main amd64 Packages 100 /var/lib/dpkg /status 1.9.15-0ubuntu1 500 500 http://sg.mirrors.cloud.aliyuncs.com/ubuntu xenial/main amd64 Packages My nginx service config is like: nano /lib/systemd/system/nginx.service # Stop dance for nginx # ======================= # # ExecStop sends SIGSTOP (graceful stop) to the nginx process. # If, after 5s (--retry QUIT/5) nginx is still running, systemd takes control # and sends SIGTERM (fast shutdown) to the main process. # After another 5s (TimeoutStopSec=5), and if nginx is alive, systemd sends # SIGKILL to all the remaining processes in the process group (KillMode=mixed). # # nginx signals reference doc: # http://nginx.org/en/docs/control.html # [Unit] Description=A high performance web server and a reverse proxy server After=network.target [Service] Type=forking PIDFile=/run/nginx.pid ExecStartPre=/usr/sbin/nginx -t -q -g 'daemon on; master_process on;' ExecStart=/usr/sbin/nginx -g 'daemon on; master_process on;' ExecReload=/usr/sbin/nginx -g … -
Searching a few colums in Django
So I got a a Database with a few colums. I want to add to my search the option to search not only one column like Project. I want to search a few more colums too.. so the search will look for Project or ServerName or IP and search all of the colums or a few of them. Any idea? I tried (Project__icontains=query, ServerName__icontains=query) but it said wrong syntax. index.html- def get(self, request): form = HomeForm() query = request.GET.get("q") posts = serverlist.objects.all() if query: posts = serverlist.objects.filter(Project__icontains=query) else: posts = serverlist.objects.all() # else: models.py - from django.db import models class serverlist(models.Model): ServerName = models.CharField(max_length = 30) Owner = models.CharField(max_length = 50) Project = models.CharField(max_length = 30) Description = models.CharField(max_length = 255) IP = models.CharField(max_length = 30) ILO = models.CharField(max_length = 30) Rack = models.CharField(max_length = 30) Status = models.CharField(max_length = 30) -
Django importing app models in non-app package
I have a django project with two apps, and I also want to have a scheduled job via Heroku's job scheduling tools which handles some regular database operations. In order to handle the tasks of the scheduled job, I have a separate package in my top-level django project folder. This package requires access to the models as defined in my apps. However, I cannot find out how to import the models from my apps. The structure is as follows: myproject | | myproject | | __init__.py | | ... | myapp1 | | __init__.py | | models.py | | ... | myapp2 | | __init__.py | | models.py | | ... | customjobmodule | | __init__.py | | ... | ... I have tried several ways of importing using sys.path.append() but none of them seem to work. They all say there is no module named myapp1.models import os import sys cwd = os.getcwd() sys.path.append(cwd + '/../myapp1/') from myapp1.models import Model1 ImportError: No module named myapp1.models Is there a way to do this? When searching around I have found plenty of information about using models between django apps, but not using them outside of the django framework altogether. -
Why Django Rest Framework SessionAuthentication doesn't require csrf for unauthenticated users?
I've found this in Django Rest Framework docs: CSRF validation in REST framework works slightly differently to standard Django due to the need to support both session and non-session based authentication to the same views. This means that only authenticated requests require CSRF tokens, and anonymous requests may be sent without CSRF tokens By default DRF uses those authentication classes: 'DEFAULT_AUTHENTICATION_CLASSES'= ( 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.BasicAuthentication' ), What would be the problem in supporting both session and non-session based authentication while checking csrf token for unauthenticated users (using SessionAuthentication class)? -
Memcache status not working for Django 1.11 and Python 3.6
I installed memcached for my django project (Django 1.11 and Python 3.6). When I add the memcached_status to my installed apps in settings.py, I get this error when I try to open the Django admin page: Internal Server Error: /admin/ Traceback (most recent call last): File "/Users/comp/Desktop/Dev/educa/lib/python3.6/site- packages/django/core/handlers/exception.py", line 41, in inner response = get_response(request) File "/Users/comp/Desktop/Dev/educa/lib/python3.6/site- packages/django/core/handlers/base.py", line 217, in _get_response response = self.process_exception_by_middleware(e, request) File "/Users/comp/Desktop/Dev/educa/lib/python3.6/site- packages/django/core/handlers/base.py", line 215, in _get_response response = response.render() File "/Users/comp/Desktop/Dev/educa/lib/python3.6/site- packages/django/template/response.py", line 107, in render self.content = self.rendered_content File "/Users/comp/Desktop/Dev/educa/lib/python3.6/site- packages/django/template/response.py", line 84, in rendered_content content = template.render(context, self._request) File "/Users/comp/Desktop/Dev/educa/lib/python3.6/site- packages/django/template/backends/django.py", line 66, in render return self.template.render(context) File "/Users/comp/Desktop/Dev/educa/lib/python3.6/site- packages/django/template/base.py", line 207, in render return self._render(context) File "/Users/comp/Desktop/Dev/educa/lib/python3.6/site- packages/django/template/base.py", line 199, in _render return self.nodelist.render(context) File "/Users/comp/Desktop/Dev/educa/lib/python3.6/site- packages/django/template/base.py", line 990, in render bit = node.render_annotated(context) File "/Users/comp/Desktop/Dev/educa/lib/python3.6/site- packages/django/template/base.py", line 957, in render_annotated return self.render(context) File "/Users/comp/Desktop/Dev/educa/lib/python3.6/site- packages/django/template/loader_tags.py", line 177, in render return compiled_parent._render(context) File "/Users/comp/Desktop/Dev/educa/lib/python3.6/site- packages/django/template/base.py", line 199, in _render return self.nodelist.render(context) File "/Users/comp/Desktop/Dev/educa/lib/python3.6/site- packages/django/template/base.py", line 990, in render bit = node.render_annotated(context) File "/Users/comp/Desktop/Dev/educa/lib/python3.6/site- packages/django/template/base.py", line 957, in render_annotated return self.render(context) File "/Users/comp/Desktop/Dev/educa/lib/python3.6/site- packages/django/template/loader_tags.py", line 177, in render return compiled_parent._render(context) File "/Users/comp/Desktop/Dev/educa/lib/python3.6/site- packages/django/template/base.py", line 199, in _render return self.nodelist.render(context) File "/Users/comp/Desktop/Dev/educa/lib/python3.6/site- … -
Django: custom users
I have following users in my Django applications: 1. Normal user (UUID, email, name, address, password) 2. Remote application (UUID, name, generated random secret) 3. (other type of remote application) The authentication for the Normal user would be with webpage email + password The authentication for the Remote application would be with UUID + random secret with JSON to ask for the temporary token I do not know how to handle this in Django. I wanted to create AuthBaseUser from AbstractBaseUser like: class AuthBaseUser(AbstractBaseUser, PermissionsMixin): pk = models.UUIDField(primary_key=True, unique=True, default=uuid.uuid4, editable=False,) name = models.CharField(_('name'), max_length=128, blank=False) typ = models.CharField(max_length=16, choices=USER_TYPES, default='normaluser',) date_joined = models.DateTimeField(_('date joined'), auto_now_add=True, default=timezone.now) last_login = models.DateTimeField(_('last login'), auto_now_add=True) is_active = models.BooleanField(_('active'), default=True) Then I wanted to create a RemoteAppUser and NormalUser with 1:1 mapping like this: class NormalUser(AuthBaseUser): user = models.OneToOneField(AuthBaseUser, on_delete=models.CASCADE) email = models.EmailField(_('email address'), unique=True) is_superuser = models.BooleanField(_('superuser'), default=True) #password = #not decided yet what to add here; for remote app we will have 256b of SHA256's random generated value EMAIL_FIELD = 'email' REQUIRED_FIELDS = AuthBaseUser.REQUIRED_FIELDS.append(['email', 'password', ]) objects = NormalUserManager() def __init__(self, *args, **kwargs): super(AuthBaseUser, self).__init__(*args, **kwargs) def __str__(self): return self.get_username() def get_full_name(self): return self.get_username() def get_short_name(self): return self.get_username() Of course, I have … -
Django RedirectView to my another project's url as default
I started to build the django tutorial app on the MDN website yesterday. And used RedirectView.as_view() to redirect my base urls to the app url as the tutorial said and it worked fine. # MDN Project urls.py urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^catalog/', include('website.urls')), url(r'^$', RedirectView.as_view(url='/catalog/', permanent=True)), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) In the catalog app: # Catalog app urls.py urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^about/$', views.about, name='about'), url(r'^contact/$', views.contact, name='contact'), url(r'^products/$', views.products, name='products'), ] But today i started another project in django and tried to make my base url include directly my app and it still redirects to the MDN projects url ('/catalog/') even there is no code that says to do that. What is wrong with my code? # Projects urls.py urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^/', include('myapp.urls')), ] In my app: # My App's urls.py urlpatterns = [ url(r'^$', views.index, name='index'), ] -
Remove # and #_=_ from returning social auth url - Django
I am using python-social-auth and django in my authentication system. At the moment, when I authenticate with either Facebook or Google, the URL returns with either /#_=_ or /# appended. I understand that these are deliberate but I'd like to remove them. I've seen a number of javascript solutions for the facebook version, but I'd like to do this from the server side. I tried to do a basic redirect: def pre_home(request): return redirect(reverse('home')) def home(request): return render(request, 'core/home.html) where I directed the auth system to pre_home on completion. I assumed this would strip off the end of the url on redirection to home, however it does not... -
How do I initialise my form in Django?
I have created a contact form on my homepage but the form does not show until I click on the submit form the first time. I.e. calling the get method. I would like to keep it as a separate view to my homepage so that when re-clicking 'submit' it does not have an impact on my homepage. Is there a way to load my 'def email' when my homepage loads? template form <form method="post" action="{% url 'home_page:email' %}"> {% csrf_token %} {# {% bootstrap_form form.as_p %}#} {{ form.as_p }} <input type="submit" value="Sign Up" class="btn btn-default"> </form> urls urlpatterns = [ url(r"^$", views.HomePage.as_view(), name="home"), url(r'^email/$', views.email, name='email'), url(r'^success/$', views.success, name='success'), ] views class HomePage(MessageMixin, TemplateView): template_name = "index.html" def email(request): if request.method == 'GET': form = ContactForm() else: form = ContactForm(request.POST) if form.is_valid(): subject = form.cleaned_data['subject'] from_email = form.cleaned_data['from_email'] message = form.cleaned_data['message'] try: send_mail(subject, message, from_email, ['admin@example.com']) except BadHeaderError: return HttpResponse('Invalid header found.') return redirect('success') return render(request, "index.html", {'form': form}) -
Setting up gunicorn and supervisor for django server
I am trying to get my server up and running with gunicorn and supervisor. Managed to get it upp with this command: $ gunicorn project.wsgi:application --bind 192.168.1.130:8000 After this I made a gunicorn_init.bash file. I got the code from several tutorials. So guess it's a common way to set up gunicorn and supervisor. The code looks like this: #!/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=- This only gives me exception is worker process like this: … -
How to send Jinja variables to Django View
I have a view in HTML whereby it displays a list of table with attendees; <table> {% for people in Attendees %} <tr> <td>{{ people.id }}</td> <td>{{ people.name }}</td> <td> <a id='deleteAttendeeButton' class="btn btn-primary btn-xs">Delete</a> </td> </tr> {% endfor %} </table> The table has a delete button for all entries and when clicked, I am using AJAX for a GET request as per below; $("#deleteAttendeeButton").on("click", function () { $.ajax({ url: '/modifyAttendee/?id={{ people.id }}', type: 'GET', }) }); I want to use AJAX to send the people.ID variable to view so that the view can determine what object to delete in the database. However, the issue is I cannot seem to pass in a jinja variable in AJAX. Am I missing something in my AJAX statement? If not, what would be an ideal solution? Note: I do not want to use 'href' in the button because I do not want to reload the page. -
Unable to use Memcached in Django 1.11 (cannot import name 'get_cache')
I want to use Memcached in my Django 1.11 project. I am using Python 3.6. I have installed memcached on my mac OSX terminal with Homebrew. After that I installed its python bindings: pip install python-memchached==1.58 I then add the necessary configurations to my settings.py project file: CACHES = { 'default': { 'BACKEND':'django.core.cache.backends.memcached.MemcachedCache', 'LOCATION':'127.0.0.1:11211', } } I two terminals, one for my local host and the second one for memcached: memcached -l 127.0.0.1:11211 When I refresh my web page I get the following error: System check identified no issues (0 silenced). October 15, 2017 - 10:47:30 Django version 1.11.6, using settings 'educa.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. Internal Server Error: / Traceback (most recent call last): File "/Users/comp/Desktop/Dev/educa/lib/python3.6/site- packages/django/template/utils.py", line 65, in __getitem__ return self._engines[alias] KeyError: 'django' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Users/comp/Desktop/Dev/educa/lib/python3.6/site- packages/django/template/backends/django.py", line 126, in get_package_libraries module = import_module(entry[1]) File "/Users/comp/Desktop/Dev/educa/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 978, in _gcd_import File "<frozen importlib._bootstrap>", line 961, in _find_and_load File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 655, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in … -
Django - having more than one foreignkey in the same model
models.py class City(models.Model): id = models.IntegerField(primary_key=True) name = models.CharField(max_length=35) countrycode = models.CharField(max_length=3) district = models.CharField(max_length=200) population = models.IntegerField(default='0') class Country(models.Model): code = models.CharField(primary_key=True, max_length=3) name = models.CharField(max_length=52) continent = models.CharField(max_length=50) region = models.CharField(max_length=26) surfacearea = models.FloatField() indepyear = models.SmallIntegerField(blank=True, null=True) population = models.IntegerField() lifeexpectancy = models.FloatField(blank=True, null=True) gnp = models.FloatField(blank=True, null=True) gnpold = models.FloatField(blank=True, null=True) localname = models.CharField(max_length=45) governmentform = models.CharField(max_length=45) headofstate = models.CharField(max_length=60, blank=True, null=True) capital = models.IntegerField(blank=True, null=True) code2 = models.CharField(max_length=2) Question 1 In the above mentioned models how can i relate code in the Country.code to City.countrycode, i am not able to do so because Country model is declared after the City model. Question 2 And how to link the Country.capital in the Country model which is a integer that relates to City.name. Note I am converting a .sql file with InnoDB Engine to Postgresql. -
mysql downloading error message
I've been trying to download a database preferably mysql for my Django project but when I use pip install, it tends to be downloading, all of a sudden it brings out an error message.. Please help, I'm on Windows -
Replacing Uploaded Django File
I'm want to replace a loaded file with a different file. My model looks like this and the document I change is doc. class GeneratedDocument (models.Model): survey = models.ForeignKey(Survey) document = models.ForeignKey( Document, blank=True, null = True) doc = models.FileField( upload_to = 'generated_docs/' ) my_state_field = StateField() objects = WorkflowObjectManager() def __unicode__(self): return u'%s | %s | %s' % (self.survey.organisation, self.document.name, self.doc) I user a ModelForm to load that initially and all works fine. When I am trying to replace doc I'm using: g = GeneratedDocument.objects.get(id=int(request.POST['g_id'])) g.doc = request.FILES['doc'] g.save() It is saving the file into the right place, ie media/generated_docs/filename BUT within the model it is only saving generated_docs/filename whereas with the original load is it saving a full URL (from http://). How do I get the file uploaded to the correct media directory and save that destination within my model? Thanks for the help -
Disable form field Django inlineformset_factory
Probably an easy one I am trying to disable (i.e. that the field is present but greyed out) the 'sub_total' field on all formset lines and use javascript to update the field with whatever values are entered into the 'price_estimate' and 'quantity' fields. I have the following models: class Requisition(models.Model): create_date = models.DateTimeField(auto_now_add=True) modified_date = models.DateTimeField(auto_now=True) description = models.CharField(max_length=128, null=True, blank=True,) total = models.DecimalField(decimal_places=2, max_digits=20, null=True) class RequisitionLine(models.Model): requisition = models.ForeignKey(Requisition) product = models.CharField(max_length=50, blank=False) quantity = models.PositiveIntegerField() price_estimate = models.DecimalField(decimal_places=2, max_digits=20) sub_total = models.DecimalField(decimal_places=2, max_digits=20, null=True) @property def get_sub_total(self): return self.quantity * self.price_estimate In my view I have Formset = inlineformset_factory(models.Requisition, models.RequisitionLine, form = forms.RequsitionForm, formset= forms.RequisitionLineForm, fields=('product', 'price_estimate', 'quantity', 'sub_total'), extra=2) In forms class RequsitionForm(forms.ModelForm): class Meta: model = models.Requisition fields = ['description'] class RequisitionLineForm(forms.BaseInlineFormSet): sub_total = forms.DecimalField(disabled=True, required=False) class Meta: model = models.RequisitionLine fields = ['product', 'quantity', 'price_estimate', 'sub_total'] In addition to the code above - I have tried to modify the sub_total field on init however, whatever I try it seems that it is ignored. Any help appreciated -
Use of database ID's in the url
Is there any reason why one should prefer to use a slug in its (public) urls instead of the database id? So, is this preferred somehow... www.example.com/comments/(?P<comment_slug>[0-9]+)/details ...to this: www.example.com/comments/(?P<comment_id>[0-9]+)/details The slug could possibly just be just a linear operation on the database id (say slug = id + secret integer), as done for example in the following: https://github.com/django-notifications/django-notifications/blob/master/notifications/utils.py