Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can calculate the real distance between two points with django gis?
from django.contrib.gis.geos import Point p1 = Point(36.74851779201058, -6.429006806692149, srid=4326) p2 = Point(37.03254161520977, -8.98366068931684, srid=4326) p1.distance(p2) Out: 2.5703941316759376 But what is the unit of this float number? If you calculate this distance, this is 229.88 Km. You can get it too using geopy: from geopy.distance import distance distance(p1, p2) Out: Distance(229.883275249) distance(p1, p2).km Out: 229.88327524944066 I have read that you can get (so so) this, if you divide the previous number for 111: (2.5703941316759376 / 111) * 10000 Out: 231.5670388897241 # kilometers Is there any way to get the real distance using only django gis? Or should I use geopy? -
Django: simple model for storing messages/notifications to/from users
I am trying to create a simple Notification/Message model for my Django app. This will store notifications from the site to the user, and messages from one user to another. A working model I had been using looks like this: class Notification(models.Model): sender = models.ForeignKey(User, on_delete=models.CASCADE, null=True, related_name='sender_notification') recipient = models.ForeignKey(User, on_delete=models.CASCADE, related_name='recipient_notification') message = models.TextField() read = models.BooleanField(default=False) recieved_date = models.DateTimeField(auto_now_add=True) A message will have 0-1 senders (0 if the message is a notification from the site to the user), and typically one recipient (when the notification is meant for one specific user - e.g., "there is a comment on your post" - or when a message has been sent from one user to another). This had been working for me. However, it occurred to me that in some cases I want to send a notification to every user. I could potentially create Notification objects in a loop: for user in User.objects.all(): Notification.objects.create(recipient=user, message='message for all uses') But this seems like it will be pretty inefficient, and create unnecessary clutter in the database. I experimented with updating my model like this: class Notification(models.Model): sender = models.ForeignKey(User, on_delete=models.CASCADE, null=True, related_name='sender_notification') recipient = models.ManyToManyField(User) message = models.TextField() read = models.BooleanField(default=False) recieved_date … -
mailgun sent attachments are 1kb blank images
I have a very simple django based server i wish to use as an email sending server with mailgun I've managed to create a server endpoint that trigger an email with an attachment, this seems to work fine but when checking out the received email the attachment jpg file is just a 1kb blank image, im not sure if its a django issue, mailgun or even the fact that its a sandbox domain here is my code including imports: from django.shortcuts import render from django.http import HttpResponse from rest_framework import generics import requests class Email(generics.GenericAPIView): def post(self, req, *args, **kwargs): response = requests.post("https://api.mailgun.net/v3/sandbox....mailgun.org/messages", auth=("api", "<API_KEY>"), files=[("attachment", open("files/test.jpg"))], data={"from": "Dummy user <mg.mymail@gmail.com>", "to": ["mymail@gmail.com"], "subject": "Hello worlds", "text": "testing this thing out"}) resString = str(response) return HttpResponse(resString) -
Change name of the "Authentication and Authorization" menu in Django/python
I'm learning python/Django and setting up my first project. All is going well but I've searching like crazy on something very simple. U have the default menu item "Authentication and Authorization" and I want to change the name. I've searched in the template if I needed to extend somewhere, i've search if there's a po file or what not but I can't find it nor a hint on which parameter I should overwrite in admin.py to set it. I'm not trying to install multi language or some advanced localisation, just want to change the name of that 1 menu item :) Any ideas? Tx! Z -
JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)
I have a model JsonField in django app, and the result storing in that field was print obj.json_field_data "{u'Field_number_one': u'one', u'Field_number_two': u'two', u'Field_number_three': u'three'}" I am trying to load the above data using simplejson as below import simplejson simplejson.loads(obj.json_field_data) result lib/python2.7/site-packages/simplejson/__init__.pyc in loads(s, encoding, cls, object_hook, parse_float, parse_int, parse_constant, object_pairs_hook, use_decimal, **kw) 514 parse_constant is None and object_pairs_hook is None 515 and not use_decimal and not kw): --> 516 return _default_decoder.decode(s) 517 if cls is None: 518 cls = JSONDecoder /Users/username/.virtualenvs/project/lib/python2.7/site-packages/simplejson/decoder.pyc in decode(self, s, _w, _PY3) 368 if _PY3 and isinstance(s, binary_type): 369 s = s.decode(self.encoding) --> 370 obj, end = self.raw_decode(s) 371 end = _w(s, end).end() 372 if end != len(s): /Users/username/.virtualenvs/project/lib/python2.7/site-packages/simplejson/decoder.pyc in raw_decode(self, s, idx, _w, _PY3) 398 elif ord0 == 0xef and s[idx:idx + 3] == '\xef\xbb\xbf': 399 idx += 3 --> 400 return self.scan_once(s, idx=_w(s, idx).end()) JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1) So whats wrong with the above json data that i am getting from django field ? -
Django include template tag multiple template choices
I have a requirement where in I have to include a template inside a template tag. But the template I want to include is not fixed. I have list of templates and whichever is found first need to be included. The include template tag however takes only a single template name. Is there a way to modify this behavior or any other way to achieve this. I was using custom template tag for the same, but I am getting warning since updating to django 1.9 that RemovedInDjango110Warning: render() must be called with a dict, not a RequestContext. return t.render(context) This is my custom template tag @register.simple_tag(takes_context=True) def custom_include(context, *template_choices): template_choices = (context['optionalTemplate'],) + template_choices t = template.loader.select_template(template_choices) return t.render(context) Can anyone suggest how to achieve this. -
Invalid Token 0644 File Permission Django
I am trying to get this Django Project to run locally https://github.com/vitorfs/bootcamp I am following the installation guide https://github.com/vitorfs/bootcamp/wiki/Installing-and-Running-Bootcamp but when I try to migrate I get this error (bootenv) Emils-MacBook-Air:bootcamp emilrasborgpaulsen$ pip install psycopg2 Collecting psycopg2 Using cached psycopg2-2.6.2.tar.gz Complete output from command python setup.py egg_info: running egg_info creating pip-egg-info/psycopg2.egg-info writing pip-egg-info/psycopg2.egg-info/PKG-INFO writing top-level names to pip-egg-info/psycopg2.egg-info/top_level.txt writing dependency_links to pip-egg-info/psycopg2.egg-info/dependency_links.txt writing manifest file 'pip-egg-info/psycopg2.egg-info/SOURCES.txt' warning: manifest_maker: standard file '-c' not found Error: pg_config executable not found. Please add the directory containing pg_config to the PATH or specify the full executable path with the option: python setup.py build_ext --pg-config /path/to/pg_config build ... or with the pg_config option in 'setup.cfg'. ---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in /private/var/folders/8l/nwwcj_1d2k5_wf3td439ftfh0000gn/T/pip-build-w76_ywwu/psycopg2/ So I tried to remove psycopg2 and migrate it, then I receive FILE PERMISSION 0644 Invalid Token. I did that to try and install psycopg2 using pip. I am using a virtual env on a macbook air. I am quite new to this python/django. Best regards E -
Django 1.7 tests against production DB rather than create test DB
I've been handed a django-1.7 installation and asked to make testing work for an in-house django module. (specifically, we're running Django==1.7.9 and psycopg2==2.5.4) After two days of head scratching, I'm still finding that when I run manage.py test mymodule, it's testing against the production postgres database rather than creating a test database into which to install my fixture data. Weirdly, I don't get any error messages or any indicators that it's trying to create a test database at all. The testsuite simply tests against the production database. I've verified that the user I'm running as has CREATE/DROP privileges in postgres for a test database. I've also tried to get my testsuite to use an in-memory database by specifying a TEST database engine as the built-in sqlite3, per the docs, like so: DATABASES = { 'default': { 'NAME': DATABASE_NAME, 'PASSWORD': 'nottherealpassword', 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'USER': 'nottherealdbuser', 'PORT': '5432', 'HOST': '127.0.0.1', 'TEST': { 'ENGINE': 'django.db.backends.sqlite3' } }, } No change in behavior with this configuration, either, and no indication that it's even trying to create one. Is there some scenario in which the test runner declines to even attempt to create a test database for a given module? I've tried both the default … -
How to solve "Application Error" in Heroku (Python)
I created a project in Python-Django framework.I deploy the project in heroku. When I'm trying to use heroku open command on terminal, I got Application Error An error occurred in the application and your page could not be served. Please try again in a few moments. If you are the application owner, check your logs for details. Please help me to solve this error. -
Concatenating filter requests with a loop in django
I have a list of strings that I need to determine if they are present in my model names. Currently I am using a series of if and elif statements to determine how many strings are in my list of strings then execute a filter request to my database like this (this works but is extremely inefficient as I am constantly repeating myself): #example if my list contained only 2 strings if len(listOfStrings) == 2: queryResults = MyModel.objects.filter(Q(name__contains=listOfStrings[0])|Q(name__contains=listOfStrings[1])) Then I notify the client based on the result of these queries. If I test the strings against my models each individually I might get the same models (because some model names contain all three or two strings) then notify the client twice. So I would think to solve this problem using a for loop like so listOfStrings = {"string1","string2","string3"} queryResults = "" for string in listOfStrings: queryResults += MyModel.objects.filter(name__contains=string) I understand that the filter() method is lazy and doesn't execute right away and that this python logic is most likely wrong. But how do I concatenate filter requests in order to avoid duplicate model results. -
Django changes the remote Mysql IP address
We are running an API using Django, hosted in Amazon EC2, with one instance for the API and one instance for the Database. The API machine is running nginx and uwsgi, and when we try to connect to the remote mysql database using either the private or public IP of the database machine, and I try to load the page or any resource I get a OperationalError at /resource/ (1045, "Access denied for user 'user'@'localIP' (using password: YES)") So it is basically trying to connect to mysql locally, when I'm using the remote IP in the hosts field in the database settings in django. Uwsgi and nginx logs aren't of any help at all, and we have tried messing with the database config in settings.py, setting debug to false, changing the allowed hosts, etc. Thanks in advance. -
Filtering object model django with list of values
I am building a django project and I have a list of ids [23,44,12,67] and I have a model named testmodel tests = testmodel.objects.all() But I want to remove/filter(I don't want to remove from database, just filter) the objects which has the ids in my list. Any help how I can achieve this in a simple way using django ? -
Data Migrations on Django getting previous Model versions
Im working on a data migrations which needs to change a Foreign key to a different model and alter all the existing instances foreign keys to the new Model pk. I think this can be achieved with data migrations on Django. My question is: ¿How can I acces previous versions of my models in order to perform the data migration? I would like to do something like this: MyPreviousModel = previousModels.MyModel ModelAfterMigration = afterMigrations.MyModel all_previous = MyPreviousModel.objects.all() for element in all_previous: element.previous_fk = new_foreignKey ModelAfterMigrations.create(element) -
Why my code is not encrypting the password if i inherit django user?
Im learning about django, and i need create a customized user, called Person. I use inherit from contrib.auth.models User, but in my django administrator the form for add a new Teacher dont show the field confirm password and the password is not encrypted in the table user from django.db import models from django.contrib.auth.models import User, UserManager # Create your models here. class Person (User): date_of_birth = models.DateField(blank=False, null=False) class Meta: abstract = True class ClassRoom (models.Model): classroom = models.CharField(max_length=3, blank=False, null=False) def __unicode__(self): return self.classroom class Teacher(Person): phone = models.PositiveIntegerField(max_length=15, blank=False, null=False) classroom = models.ManyToManyField(ClassRoom) You can see in this photo as the first and second users is saved encripting the password(this users was added as normal user in the django administrator), but the last(creadted as Teacher in the django administrator) dont encrypt the pass. ¿Someone can help me? database photo user table -
Sort django queryset using a Python list
I have a Model Car(self.Models) # a bunch of features here then in my views.py, I get all the cars and compute a score for them: allCars = Car.object.all() # so you get [A, B, C, D] scoreList = someComputation(allCars) # returns [3,1,2,4] then in my template I iterate through allCars to display them; using the ordering the query returned with I get primary key ordering, so A B C D However I would like to know if there is a way to order the queryset using the list I computed in the view, which would yield B C A D so doing something like allCars.order_by(scoreList) -
django.db.utils.IntegrityError: (1048, "Column 'create_timestamp' cannot be null")
This is the full output after execute script this error is present when run script on python I use django 1.10 python 2.7 File "/usr/bin/snort-sig-parser.py", line 213, in <module> main() File "/usr/bin/snort-sig-parser.py", line 205, in main sig_parse(sig_line, 0,options.branch,options.revision) File "/usr/bin/snort-sig-parser.py", line 173, in sig_parse sig_obj.save() File "/usr/local/lib/python2.7/site-packages/django/db/models/base.py", line 796, in save force_update=force_update, update_fields=update_fields) File "/usr/local/lib/python2.7/site-packages/django/db/models/base.py", line 824, in save_base updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields) File "/usr/local/lib/python2.7/site-packages/django/db/models/base.py", line 908, in _save_table result = self._do_insert(cls._base_manager, using, fields, update_pk, raw) File "/usr/local/lib/python2.7/site-packages/django/db/models/base.py", line 947, in _do_insert using=using, raw=raw) File "/usr/local/lib/python2.7/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/usr/local/lib/python2.7/site-packages/django/db/models/query.py", line 1043, in _insert return query.get_compiler(using=using).execute_sql(return_id) File "/usr/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 1054, in execute_sql cursor.execute(sql, params) File "/usr/local/lib/python2.7/site-packages/django/db/backends/utils.py", line 79, in execute return super(CursorDebugWrapper, self).execute(sql, params) File "/usr/local/lib/python2.7/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) File "/usr/local/lib/python2.7/site-packages/django/db/backends/mysql/base.py", line 117, in execute six.reraise(utils.IntegrityError, utils.IntegrityError(*tuple(e.args)), sys.exc_info()[2]) File "/usr/local/lib/python2.7/site-packages/django/db/backends/mysql/base.py", line 112, in execute return self.cursor.execute(query, args) File "/usr/local/lib/python2.7/site-packages/MySQLdb/cursors.py", line 205, in execute self.errorhandler(self, exc, value) File "/usr/local/lib/python2.7/site-packages/MySQLdb/connections.py", line 36, in defaulterrorhandler raise errorclass, errorvalue django.db.utils.IntegrityError: (1048, "Column 'create_timestamp' cannot be null") this script not write on mysql database. -
Get all objects where related object has non-blank field in Django ORM?
I've got two models: Company: pk ... Supplier: pk mobile_phone = models.CharField(max_length=200, default='', blank=True, verbose_name="Мобильный телефон") company_id ... So: Company may have many Suppliers Supplier may belong to one Company How to get all Companies, which have at least one Supplier with non-blank mobile_phone? Tried: return queryset.filter(suppliers__mobile_phone__iregex=r’^(?!\s*$).+’) Returns queryset with duplicates return queryset.exclude(suppliers__isnull=True).exclude(suppliers__mobile_phone__exact=‘’) Doesn't work when Company has 2 suppliers, which of them doen't have mobile_phone. Any help // link to docs is appreciated. -
Logs not getting created in Django Project
My Django project is not creating logs, this is the Logging info in my setting.py: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'file': { 'level': 'DEBUG', 'class': 'logging.FileHandler', 'filename': '/home/bithu/bservice/bservice/logs/djangoLog.log', }, }, 'loggers': { 'django': { 'handlers': ['file'], 'level': 'DEBUG', 'propagate': True, }, },} and this is how I call it from my views.py: import logging logger = logging.getLogger(__name__) from django.shortcuts import render from django.http import HttpResponse def test_view(request): #return 'OK' if request.method == 'POST': logger.info('checking') logger.info('checking') return HttpResponse('Testing Web Service.......') I have created the log files manually and given it 777 permission still the logs are not getting created . Can somebody shed some light on it please. -
Django Apache mod_wsgi permission errors
Have setup Django in virtualenv but get 500 Internal Server Error. Development server worked fine. Environment: Python 2.7.12 Apache 2.4.23 Django 1.10 Fedora 24 Server log: [Mon Aug 29 12:27:49.364393 2016] [mime_magic:error] [pid 19158] [client 14.2.108.225:49222] AH01512: mod_mime_magic: can't read /home/fedora/motorable/motorable/wsgi.py' [Mon Aug 29 12:27:49.364552 2016] [mime_magic:error] [pid 19158] [client 14.2.108.225:49222] AH01512: mod_mime_magic: can't read/home/fedora/motorable/motorable/wsgi.py' [Mon Aug 29 12:27:49.364904 2016] [wsgi:error] [pid 19157] (13)Permission denied: [remote 14.2.108.225:1832] mod_wsgi (pid=19157, process='motorable', application='ip-172-31-22-170.ap-southeast-2.compute.internal|'): Call to fopen() failed for '/home/fedora/motorable/motorable/wsgi.py'. Configuration: /etc/httpd/conf.d/django.conf Alias /static /home/fedora/motorable/static <Directory /home/fedora/motorable/static> Require all granted </Directory> <Directory /home/fedora/motorable/motorable> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess motorable python-path=/home/fedora/motorable:/home/fedora/mot$ WSGIProcessGroup motorable WSGIScriptAlias / /home/fedora/motorable/motorable/wsgi.py WSGISocketPrefix /var/run/wsgi WSGI is running in daemon mode, I tried adding the WSGISocketPrefix directive but I'm not sure what else to check or do. First time experimenting with Django here. The user home directory is 710 and should allowing Apache in, I added apache user to the primary group of fedora. Can anyone share some insight? -
django 1.10 translation, though language switched, no translation appeared
I'm using Django 1.10. What I want is, to add Chinese translation to my page. Although the language is switched to zh-hans, the translation does not successfully appear. I was referring to the official guide https://docs.djangoproject.com/en/1.10/topics/i18n/translation/ Here's what I have in my code. (I'm using local) settings.py: ... MIDDLEWARE = [ ... 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', ... ] TEMPLATES = [ { ... 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.i18n', ... ],},},] LANGUAGE_CODE = 'en-us' TIME_ZONE = 'Asia/Shanghai' USE_I18N = True USE_L10N = True USE_TZ = True LOCALE_PATHS = (os.path.join(BASE_DIR, 'locale')) ... index.html, which is in the "home" app: ... <!-- Current language: {{ LANGUAGE_CODE }} --> <p>{% blocktrans %}Harbor. Shelter. WC. SDK.{% endblocktrans %}</p> ... django.po, located in (root)/locale/zh_hans/LC_MESSAGES #: home/templates/home/index.html:23 msgid "Harbor. Shelter. WC. SDK." msgstr "高端黑" Then I re-compiled the message, restarted the server, and then reloaded the page. (I was using go-incognito, which means no cache existed.) From {{ LANGUAGE_CODE }} in the comment section, I could see the language was switched pretty fine, already being "zh-hans". However, the translation did not show up, the string was still "Harbor. Shelter. WC. SDK.", remaining untranslated. What was wrong? What did I miss? -
indext is missing a QuerySet. Define indext.model, indext.queryset - django
I tried to see another quiestions of peoples, and i didnt got an answer. There is my view and my url reference to the view: from django.views import generic from .models import Album class indext(generic.ListView): template_name = 'showname/index.html' context_object_name = 'albums' def albums(self): return Album.objects.all() and my urls: from django.conf.urls import include, url from . import views urlpatterns = [ url(r'^$', views.indext.as_view(), name='index'),] Everything is set well.. why doews it gives me that problem? And if i already asking, so i ask another question related: Why django made "render\httpresponse\loader" if they edventually make generic view that makes the all work for you? why they have didnt just do generic view? -
New version of django-model-utils doesn't have PassThroughManager
I use Django 1.9.9 So how can I edit my model instead of PassThroughManager? from model_utils.managers import PassThroughManager class TopicQuerySet(QuerySet): def get_topic_today(self): return self.filter(created_at__day=datetime.date.today()).order_by('title') def get_topic_popular(self): return self.annotate(entry_count=Count('entry')).order_by('-entry_count') class Topic(TimeStampModel): objects = PassThroughManager.for_queryset_class(TopicQuerySet)() Should I try to use GeoManager? -
model create using dictionary in django
In Django is it possible to create through dictionary similar as to filtering? Here is my models.py: class Personnels(models.Model): name = models.CharField(max_length=100) Here is my views.py: from . models import * def artists(request): personnels = Personnels.objects.all() if request.method == "POST": data = {"name": "Dean Armada"} Personnels.objects.create(data) However the code above will throw an error. What I really am trying to do is to do a create function coming from a "request.POST" but my views above serves as a simple example on doing it -
Auto-add image field in form wizard
Can someone show me a sample of how template files are supposed to look like when using multiple template files? Form wizard documentation is terrible. My form has 3 steps, 1 and 2 are supposed to use one template, while step 3 needs to use a separate template file for inline modelformset (apparently), for dynamically adding image upload fields (What I'm trying to do: when user first enters step3, only 1 upload button appears, after he uploads the image, another upload button appears etc. until max_num) -
Append elements to list in a django template
I am learning python and django and would like to thank all for contributing to this question. It's been a great help. I would like to append elements to a list in django template, I do not want this to be done in the views file.I have tried this Creating a list on the fly in a Django template Say i have a html template file: {% for i in reservations %} {% for j in i.Instances %} {% lis_append j.InstanceId as test %} the instanceid list is:{{test}} {% endfor %} {% endfor %} I am trying to use "lis_append" template tag to append the value of "j.InstanceId" to a context variable "test". ex: test = ['i-xxxxxx','i-xxxxxxx','i-xxxxxxx'] - Preferred output from the template tag. All I get is the instance value, one below the other and not appended to any list. ex: i-xxxxxxxx i-xxxxxxxx .... Please suggest me a way to get this done. I have written few tags which does not fetch me the required result. Kindly help. Thanks in advance!