Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
TemplateSyntaxError django link
I'm using django 1.11 and python 3. I but a link in the page when i click it i get this error. any idea? -
django-ckeditor formatting not in html post
I have an issue similar to this previous question : Django-ckeditor not displaying correctly in html except that my settings seem to be ok but still not displaying in the html page. What am I missing? settings.py INSTALLED_APPS = [ 'ckeditor', 'ckeditor_uploader', ] CKEDITOR_CONFIGS = { 'awesome_ckeditor': { 'toolbar': 'full', }, } CKEDITOR_IMAGE_BACKEND = "pillow" and in the html page rendering the edited post I have: post_detail.html <div class="post-content">{{post.text|safe|linebreaksbr}}</div> Everything works fine on the admin side: yet it is not displayed on the page: -
Django foreign key backward relation does not work
I have a class B that contains a ForeignKey relation to class A. When I instantiate B I can access field 'a' but the reverse relation (which should be created automatically) raises an error. Concretely, I have the following class definitions: from django.db.models import Model, CharField, DateField, ForeignKey from django.urls import reverse class Patient(Model): GENDER = ( ('M', 'Male'), ('F', 'Female'), ('U', 'Unknown'), ) last_name = CharField(max_length=128, null=False) first_name = CharField(max_length=128, null=False, default='') gender = CharField(max_length=1, choices=GENDER, null=False) dob = DateField(null=False) def get_absolute_url(self): return reverse('patient_detail', args=[str(self.id)]) def __str__(self): return '{}, {} ({}, {})'.format(self.last_name, self.first_name, self.gender, self.dob) class AttributeSet(Model): name = CharField(max_length=128, null=False) description = CharField(max_length=256, blank=True, default='') def get_absolute_url(self): return reverse('attribute_set_detail', args=[str(self.id)]) def __str__(self): return self.name class AttributeSetInstance(Model): patient = ForeignKey('Patient', null=False) # Automatic 'attribute_set_instance_set' backward relation? attribute_set = ForeignKey('AttributeSet', null=False) def get_absolute_url(self): return reverse('attribute_set_instance_detail', args=[str(self.id)]) def __str__(self): return self.attribute_set.name When I try to create a new AttributeSetInstance with a Patient and AttributeSet argument I can access the patient and attribute_set fields, but not vice versa. Like so: Python 2.7.13 (v2.7.13:a06454b1afa1, Dec 17 2016, 12:39:47) [GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) >>> from app.models import Patient, … -
Django how to display img in template by setting MEDIA_ROOT
here is my settings MEDIA_ROOT = 'upload/' MEDIA_URL = '/upload/' where the path of upload folder is PROJECT_ROOT/myapp/upload. I successfully upload a file a.jpg to that folder, but in the render page it shows that /upload/a.jpg not found I'm confused about the media root setting. I think it's similar to STATIC_URL, my static url setting is like this: STATIC_URL = '/static/ and the path of static folder is PROJECT_ROOT/myapp/static and files like /static/a.css can ben rendered successful in web pages. -
ValueError on migrate Django Database
Whenever I want to migrate my Django Database I get the error message above. ValueError: invalid literal for int() with base 10: 'NA' However, my models are empty. When I check them with Model.objects.all() I get . And when I look at my models at Django Admin, they are empty as well. So how is it possible that there is any "NA" where there shouldn't be one? And how can I repair my database? Thanks for any help! -
Using Highchart with javascript
I used Highchart with Django Here is my value of temperature of a javascript object . [42, 42, 42, 42, 42, 42, 42, 42, 25.9, 26, 26.1] Here is my div in html: <div id="container2" style="width:100%; height:400px;"></div> chart.js $(document).ready(function(){ var endpoint = '/api/chart/data'; var temperature = []; var humidity = []; var uv = []; var light = []; var rainfall = []; var labels = []; $.ajax({ method: "GET", url: endpoint, success: function(data){ labels = data.labels; temperature = data.temperature; console.log(temperature); setChart(temperature); }, error: function(error_data){ console.log("error"); console.log(error_data); } }); $(function setChart(temperature){ console.log(temperature); Highcharts.setOptions({ title: { text: '過去24小時氣溫變化圖' }, chart: { backgroundColor: { linearGradient: [0, 0, 500, 500], stops: [ [0, 'rgb(255, 255, 255)'], [1, 'rgb(240, 240, 255)'] ] }, borderWidth: 2, plotBackgroundColor: 'rgba(255, 255, 255, .9)', plotShadow: true, plotBorderWidth: 1 } }); var chart2 = new Highcharts.Chart({ chart: { renderTo: 'container2', type: 'column' }, xAxis: { type: 'datetime' }, series: [{ data: temperature, #data: [8,7,5,6,4,2,3,1], pointStart: Date.UTC(2010, 0, 1), pointInterval: 3600 * 1000 // one hour }] }); }); }); The chart can be printed when uncommented the data in series.(#data: [8,7,5,6,4,2,3,1], But when it replaced by data: temperature, Then the some error comes from the following codes: setChart(temperature); Uncaught … -
use unique id in django model custom save
I am trying to create unique slugs from persons names, which will have obvious duplicates. My idea is to add the id to the slug as a unique identifier. The problem is that the unique id is not generated until the save completes. This is what I tried: def save(self, *args, **kwargs): if getattr(self, 'name', True): if not self.pk: matching_slugs = Entity.objects.filter(slug=slugify(self.name)) print matching_slugs if len(matching_slugs) > 0: self.slug=slugify(self.name+' temp') elif len(matching_slugs) == 0: self.slug=slugify(self.name) super(Entity, self).save(*args, **kwargs) self.slug=slugify(self.name+' '+str(self.id)) self.save() I get the error: maximum recursion depth exceeded in cmp I'm thinking this is not the best way to do this. How can I make names unique on save? -
Would installing LAMP fix Django/MySQL config issues?
Excuse me for the very broad question, but I seem to be going around in circles. I'm looking to build/develop a "web" app, using a MySQL database and host it on my RPi. In trying to do so, I've learnt that I need a webserver (apache2 seems to be the one these days) and that I needed to create an "app" to interface between them. Initially, I was using Python and Qt to try and build an app to be the interface, but found out that things weren't simple and I used to use Python/MySQL connectors etc. After a few weeks, I got things connected and then thought about the building of it. It became apparent that options like Flask & Django would be better suited for the task due to the frameworks. I found the DjangoGurls tutorial simple to follow when I read through it, so decided to give it a go, and just had to work out to substitute their PythonAnywhere.com deployment example, with my own server..........stuck. I've got things working on my laptop/development environment, but the server side of things isn't behaving. I know it's to do with the MySQL config/settings/permissions/path but I can't pinpoint it. There … -
Develop a mobile application based on an existing Django website/app
We have a website written in Django, that has been running for a few years. Now we would like to develop a mobile application for Android and iOS, using as much as possible from the Django-site. E.g. classes from models, like users and relevant functions, other data, etc What would be the best/easiest way to approach this issue. We have been looking at several other questions like this, but all seem to be a few years old Is there any options to using e.g. Django REST API? We are just a group of students, and any help/pointers on where to start would be much appreciated! -
Creating a queryset that subtracts 2 decimalfields
debts = Debt.objects.filter(debt_closed=False) for debt in debts: if debt.product.product_price - debt.product_paid <= 0: debt.debt_closed = True debt.save() debt.product.product_price and debt.product_paid are decimals. I need to subtract these two values in order to verify that the debt has been paid, so i can set mark boolean debt_closed true. The problem is, I will have to get every object, even the debts that are not paid yet. Is there any way to create a queryset that matches this condition? -
Django how to make flexible generic views
How do you make flexible generic views? At the moment I have two models one for apples and one for pears, and a single template I want to use. class AppleIndexView(generic.list): template_name = 'fruit/index.html' context_object_name = 'apple_list' def get_queryset(self): return Apple.objects.values() class PearIndexView(generic.list): template_name = 'fruit/index.html' context_object_name = 'pear_list' def get_queryset(self): return Pear.objects.values() Is there a way of being more DRY? There should be a better way. Thank you for your time -
Django How to get user (authenticated) ID in order to save data submitted by an anonymous user?
I am trying to let an anonymous user submit data through a modelform which is on a user's profile page and have that data saved (once submitted) to the user whose profile it was on. The approach I was thinking was to take in a 'pk' parameter to my view function (from my url pattern) and somehow correlate it to the user id of the page they are on and save it. Is there a way to get the user id of the profile page the anonymous user is submitting the form on? Or is there a better approach to doing this altogether? My model uses a foreign key to the authenticated User. I have one model which is a model for ideas (called Ideas) and they all belong to one user. And as new profiles get created, each user will have their own set of ideas and so on. Any help is greatly appreciated! -
Converting python2 library to python3
I have installed django-socketio using pip in my windows machine. Later I realized it has written in python2. I removed the package using the command pip uninstall django-socketio Then I downloaded the source code from here and refactored for python3 and installed it using the command python setup.py install but my example code still referring the python2 version code from somewhere. I haven't create any virtual environment. Any suggestions about what I have done wrong. Here is a part of my stacktrace.. ... File "<frozen importlib._bootstrap_external>", line 759, in source_to_code File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed File "../..\django_socketio\management\commands\runserver_socketio.py", line 57 print "SocketIOServer running on %s:%s" % bind ^ SyntaxError: Missing parentheses in call to 'print' If there is a way to find django-websocktio for python3 or good suggestion will be much helpful. Thank you. -
After switching from Django's default Users model to an AbstractUser model, Admin is looking for a Users_groups table
It became apparent the default User model wasn't going to work for me, nor extending it, so decided to make an AbstractUser model to use an existing table. Pretty much have everything working, except when I go to edit a user in Django Admin, I am getting an error: ProgrammingError at /adminauthentication/user/100826/change/ (1146, "Table 'test_db.Users_groups' doesn't exist") Not sure why it is trying to find this table as I haven't specified it, don't recall in the documentation needing to specify it, and thought AbstractUser would use other default tables that created with the initial migrate (e.g. auth_group or something). Not quite sure how to resolve, but I am looking into it. # ./admin.py from django.contrib import admin from django.contrib.auth.admin import UserAdmin from .models import User admin.site.register(User, UserAdmin) # ./models.py from django.db import models from django.contrib.auth.models import AbstractUser # Create your models here. # Extend the User model class User(AbstractUser): id = models.AutoField(primary_key=True) username = models.CharField(max_length=255, blank=False, null=False, unique=True) first_name = models.CharField(max_length=255, blank=True, null=True) last_name = models.CharField(max_length=255, blank=True, null=True) email = models.CharField(max_length=255, blank=True, null=True) phone = models.CharField(max_length=255, blank=True, null=True) password = models.CharField(max_length=255, blank=True, null=True) ip_whitelist_1 = models.CharField(max_length=32, blank=True, null=True) ip_whitelist_2 = models.CharField(max_length=32, blank=True, null=True) ip_whitelist_3 = models.CharField(max_length=32, blank=True, null=True) last_login = … -
Have Django traceback pinpoint where error occurred?
I have two questions about Django tracebacks. First, if I have a traceback like the following, I can see that the error is occurring in the 'review_new_profile' view as shown in the second traceback error below. Is it possible to tell Django to also display the line number in that view where the error occurred? /srv/http/example.com/venvs/725be8a8537aeef8021231ba68de3184bbd547b1/local/lib/python2.7/site-packages/django/core/handlers/base.py in get_response 1. response = wrapped_callback(request, *callback_args, **callback_kwargs) /srv/http/example.com/repo/profile/views.py in review_new_profile 1. user = User.objects.get(id=request.session['uid']) /srv/http/example.com/venvs/725be8a8537aeef8021231ba68de3184bbd547b1/local/lib/python2.7/site-packages/django/contrib/sessions/backends/base.py in __getitem__ 1. return self._session[key] What I'd like to see is something like the following where '540' is the line number in the views.py: /srv/http/example.com/repo/profile/views.py in review_new_profile (540) 1. user = User.objects.get(id=request.session['uid']) Second, am I correct in in thinking that the error actually occurred at the bottom-most line? So an interpretation of this trace is that Django was trying to generate a response to a request but when it tried to get a user instance for a given uid, it couldn't find the uid in the session? In other words, the error actually occurred on the last line in the traceback, where Django was trying to get the uid (key) from the session? -
Get random point from django PolygonField
TL,DR; I want to get a random point from a polygon (potentially) using ST_GeneratePoints. Background I'm making a GeoDjango webservice and have a collection of UK Postcodes with respective boundaries like so: from django.db import models as dj_models from django.contrib.gis.db import models as gis_models class Postcode(gis_models.Model): pretty_postcode = dj_models.CharField( max_length=8 ) coords = gis_models.PolygonField( default='POLYGON EMPTY' ) I've found a delightful little PostGis function ST_GeneratePoints, it can find me random points in my coords region. Your Challenge Your mission if you so choose it, is to show how to use this function from within my python django app (or suggest a better way). Ideally ending up with a function like so: from django.contrib.gis import geos # ... other imports ... class Postcode(gis_models.Model): # ... fields ... def get_random_point(self): rand_point = # code that executes ST_GeneratePoints # and returns a geos.Point instance return rand_point -
getting null when using Where clause in python sql
I have a table userToken with three columns: piEmail , piCode, piToken This is how I created this table: class UserToken(models.Model): piEmail = models.CharField(max_length=128) piCode = models.CharField(max_length=128) piToken = models.CharField(max_length=128, unique=True, default=uuid4) piToken is autoFill, I do not insert this value. Now I am inserting value in this table and in the next line trying to fetch the token value for the random value which I inserted in table: random_number = User.objects.make_random_password(length=10, allowed_chars='123456789abcdefghijklmno') userToken_instance = UserToken.objects.create(piEmail='abc@abc.com', piCode=random_number) cursor = connection.cursor() cursor.execute("SELECT piToken FROM app_usertoken where piCode = %s", (random_number,)) row = cursor.fetchall() But it is returning null , when I check in the table, value is there. -
NoReverseMatch at / having difficulties passing datasource to form action method
NoReverseMatch at /providers/121/update/ Reverse for 'provider_update' with arguments '(None,)' not found. 1 pattern(s) tried: ['providers/(?P\d+)/update/'] I know why the NoReverseMatch error is thrown, because the url cannot find parameters being identified. However, I don't understand why my parameters are not being passed to the right view. When I pass a var holding the parameters ID or PK it recognizes it as None, for some reason. I have looked at similiar questions, but they aren't having issues passing the data to the form action. Any help is appreciated!! Thanks partial_provider_update.html <form method="post" action="{% url 'provider_update' form.instance.id %}" class="js-provider-update-form"> {% csrf_token %} <div class="modal-header"> <h4 class="modal-title">Update Provider</h4> </div> <div class="modal-body"> {% include 'providers/includes/partial_provider_form.html' %} </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> <button type="submit" class="btn btn-primary">Update provider</button> </div> </form> partial_provider_list.html {% for provider in object_list %} <tr> <td>{{ provider.id }}</td> <td>{{ provider.name }}</td> <td>{{ provider.organization }}</td> <td>{{ provider.emr }}</td> <td>{{ provider.date|date:"Y-m-d" }}</td> <td style="width: 100px; vertical-align: center; padding-top: 9px"> <button type="button" style="height: 25px; font-size: 16px;width: 50px; padding: 0px" class="btn btn-warning btn-sm js-update-provider" data-url="{% url 'provider_update' provider.id %}"> Edit </button> </td> {% empty %} <tr> <td colspan="5" class="text-center bg-warning">No Providers</td> </tr> {% endfor %} urls.py from django.conf.urls import url, include from django.views.generic import … -
Python, Django : Foreignkey accross apps is not working
Python :3.6.2 Django : 1.11.4 We are trying to use foreignkey across apps. Address is consumed by both customer and agent. We are also using inline frameset. If I put all this in one app, it is working fine including inline frameset. If I split into multiple apps, I have this error. Please see the pictures below. Foreignkey error Project folder structure Please note the apps the above folder structure. sharedmodels/models.py from django.db import models #from apps.agent.models import Agent class ContactInfo(models.Model): mobile_no = models.CharField(max_length=8) phone_no = models.CharField(max_length=10) class Location(models.Model): location_name = models.CharField(max_length=50) city = models.CharField(max_length=20, blank=True, null=True) state = models.CharField(max_length=20, blank=True, null=True) class Address(models.Model): #agent = models.Foreignkey(Agent) address1 = models.CharField(max_length=100) address2 = models.CharField(max_length=100) agent/models.py from django.db import models from apps.sharedmodels.models import Location, Address, ContactInfo class Agent(models.Model): first_name = models.CharField(max_length=20) location = models.ManyToManyField(Location) address = models.Foreignkey(Address) contactinfo = models.OneToOneField(ContactInfo) customer/models.py from django.db import models #from apps.agent.models import Agent, Address from apps.sharedmodels.models import ContactInfo, Address class Customer(models.Model): first_name = models.CharField(max_length=10) #address = models.OneToOneField(Address) contactinfo = models.OneToOneField(ContactInfo) address = models.Foreignkey(Address) Settings.py - installapps section # Application definition INSTALLED_APPS = [ 'apps.customer', 'apps.agent', 'apps.sharedmodels', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] -
In Django, how can we get all cache keys stored in database (MySQL)
I am using per-view cache in Django and I want to refresh the cache whenever it get's stale. In the documentation I see no information on refreshing stale cache and after going through several threads I decided to use django-signals to send a signal to a function which will delete the cache records from DB. So my problem is how do we retrieve the keys and delete it? I see the default implementation provides a way to give an expiration time to cache (as in @cache_page(60 * 15) and it refreshes whenever we call the view after expiration time. Is there any way to refresh stale cache not based on predefined time? -
Multiple group by and join statements in Django
I have a following query in raw SQL and I want to rewrite it using Django ORM. SELECT id, username, COALESCE(total, 0) as total, COALESCE(sum1, 0) as sum1, COALESCE(sum2, 0) as sum2, COALESCE(sum3, 0) as sum3, COALESCE(sum4, 0) as sum4, COALESCE(sum5, 0) as sum5 FROM (SELECT s_id, SUM(am) AS total FROM S GROUP BY s_id ORDER BY total) AS total LEFT OUTER JOIN ( SELECT s_id, SUM(am) AS sum1 FROM submitted WHERE category = ‘m’ GROUP BY s_id ) AS sum1 USING (s_id) LEFT OUTER JOIN ( SELECT s_id, SUM(am) AS sum2 FROM submitted WHERE category = ’s’ GROUP BY s_id ) AS sum2 USING (s_id) I can group by a table in Django using: S.objects.values('s_id').annotate(total=Sum('am')) The problem is I need somehow to join this result with the table S and then again and again. Is there a way to accomplish than using Django ORM? -
docker-compoes.yml settings with Django + Gunicorn + NGINX does not work on `docker-compose up`
This is my folder structure. ./awesome_app ├── awesome_app │ ├── celery.py │ ├── __init__.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── awesome_app_to_do_list ├── db.sqlite3 ├── docker-compose.yml ├── Dockerfile ├── logs │ ├── nginx-access.log │ └── nginx-error.log ├── manage.py ├── nginx │ └── nginx.conf ├── requirements.txt ├── run └── start.sh This is my nginx.conf. upstream awesome_app { server unix:/home/notalentgeek/Downloads/awesome_app/run/gunicorn.sock fail_timeout=10s; } server { client_max_body_size 4G; listen 8080; access_log /home/notalentgeek/Downloads/awesome_app/logs/nginx-access.log; error_log /home/notalentgeek/Downloads/awesome_app/logs/nginx-error.log warn; location /static/ { autoindex on; alias /home/notalentgeek/Downloads/awesome_app/static/; } location / { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_redirect off; if (!-f $request_filename) { proxy_pass http://awesome_app; break; } } } This is my docker-compose.yml. version: "3" services: nginx: image: nginx:latest container_name: nginx_awesome_app ports: - "8080:8080" volumes: - ./:/src - ./nginx:/etc/nginx/conf.d depends_on: - web web: build: ./ container_name: django_awesome_app volumes: - ./:/src expose: - "8080" This is my start.sh. #!/bin/bash # PENDING: From the source here, # http://tutos.readthedocs.io/en/latest/source/ndg.html it says that it is a # common practice to have a specific user to handle the webserver. SCRIPT=$(readlink -f "$0") BASEDIR=$(dirname "$SCRIPT") DJANGO_SETTINGS_MODULE=awesome_app.settings DJANGO_WSGI_MODULE=awesome_app.wsgi NAME="awesome_app" NUM_WORKERS=3 VENV_BIN=${BASEDIR}"/venv/bin" SOCKFILE=${BASEDIR}"/run/gunicorn.sock" echo $SOCKFILE SOCKFILEDIR="$(dirname "$SOCKFILE")" VENV_ACTIVATE=${VENV_BIN}"/activate" VENV_GUNICORN=${VENV_BIN}"/gunicorn" # Activate the virtual environment. cd $BASEDIR source $VENV_ACTIVATE export DJANGO_SETTINGS_MODULE=$DJANGO_SETTINGS_MODULE export PYTHONPATH=$PYTHONPATH:$BASEDIR # Create … -
Django:csrf token
When ever i am submitting the form i am getting csrfmiddlewaretoken=Mlhg830h3mLCuVD0sl1MTXUnSxFHMib6ZYtXmfZ8k1jZL1DA2IrNwzGVp2PymTCN&choice=1 in my url, even after including the csrf token also {% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %} <form> {% csrf_token %} {% for choice in question.choice_set.all %} <input type="radio" name="choice" id="choice{{ froloop.counter }}" value="{{ choice.id }}"> <label for="choice{{ forloop.counter }}" >{{ choice.choice_text }}</label><br/> {% endfor %} <input type="submit" value="Vote" /> </form> I have 'django.middleware.csrf.CsrfViewMiddleware' in my middleware settings. How to resolve this issue -
DJango Python File Upload how to preserve orginal file
I am trying to upload a file using Rest to a DJango Python API. But I noticed the file gets modified. Specifically a content-disposition is added to it. I haven't found a good way to remove this. The problem is I am trying to upload a tar that needs to be unzipped, but the modified content prevents unzipping the file. I’m using this file parser on a rest page: from rest_framework.parsers import FileUploadParser The following code seems to get the file for me in the post method of an APIView file_obj = request.FILES['file'] scanfile.file.save(file_obj.name, file_obj) Where scanfile is a model with a file field. The file gets saved with contents like this: --b3c91a6c13e34fd5a1e253b1a72d63b3 Content-Disposition: form-data; name="exclusion_file"; filename="exclusionlist.txt" My tar file contents here..... --b3c91a6c13e34fd5a1e253b1a72d63b3 My client looks like this: filename = "requirements.txt" exclusion = "../../exclusionlist.txt" headers = {'Content-Type': 'multipart/form-data;’, 'Authorization': 'JWT %s' % token, } url = "http://localhost:%s/api/scan/DysonGlobal/%s/" % (port, filename) #files = {'file': open(filename, 'rb'), 'exclusion_file': open(exclusion, 'rb')} # also tried this way but it just put the info in the same file and I see the headers in the file files = [('file', open(filename, 'rb')), ('file', open(exclusion, 'rb'))] x = requests.post(url, files=files, headers=headers) -
How to speed up Django when doing new changes to the views.py and urls.py?
Currently we have our production Django web app hosted in IIS and we have noticed that when we add new changes into the views.py or, specially, the url.py files, the changes take a while to be reflected in the server, that is, it can take an hour to see the changes. This does not happen when I modify the html files, changes take effect immediately. We also broke on purpose the url.py file by adding incorrect lines such as url1234567(r'^tickets/$', views.tickets_calculate), but this line did not take effect until several minutes later. Questions Why do the changes in these files take so long? How can I speed up this process of "refreshing of views.py and urls.py?