Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django manage.py unable to use Python protobuf C++ implementation
I'm trying to use Python protobuf C++ implementation, and was able to use it from the command line. export PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION=cpp export LD_LIBRARY_PATH=/usr/local/lib/ /myapp/bin/python myscript.py However when I tried to use Django manage.py /myapp/bin/python /myapp/app/manage.py myscript I got Traceback (most recent call last): File "/myapp/app/manage.py", line 25, in <module> __import__('mymodule.scripts.' + script, fromlist=['mymodule.scripts']).main() File "/myapp/app/mymodule/scripts/myscript.py", line 4, in <module> import mycompany.protobuf.data_pb2 as pb File "/myapp/src/mycompany-protobuf/mycompany/protobuf/data_pb2.py", line 3, in <module> from google.protobuf import descriptor File "/myapp/lib/python2.7/site-packages/google/protobuf/descriptor.py", line 45, in <module> from google.protobuf.internal import cpp_message File "/myapp/lib/python2.7/site-packages/google/protobuf/internal/cpp_message.py", line 39, in <module> from google.protobuf.internal import _net_proto2___python ImportError: libprotobuf.so.8: cannot open shared object file: No such file or directory This is what my manage.py looks like: #!/usr/bin/env python import os import sys SCRIPTS = [ 'myscript' ] if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mymodule.settings") os.environ.setdefault("PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION", "cpp") os.environ.setdefault("LD_LIBRARY_PATH", "/usr/local/lib/") if len(sys.argv) >= 2 and sys.argv[1] in SCRIPTS: import mymodule.settings as settings sys.argv.pop(0) script = sys.argv[0] __import__('mymodule.scripts.' + script, fromlist=['mymodule.scripts']).main() else: from django.core.management import execute_from_command_line execute_from_command_line(sys.argv) Notice that I have to set PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION and LD_LIBRARY_PATH inside manage.py, because when I print out os.environ inside manage.py, those environment variables are not there. I also tried copying myscript.py into /myapp/app, and then ran /myapp/bin/python /myapp/app/myscript.py and surprisingly myscript.py doesn't use … -
Django annotate : count of ModelB entries not in manytomany relationship with ModelA
In this particular case ModelA is the default Django models.User ModelB is implemented as : class ModelB(models.Model): user = models.ManyToManyField(User) #some other stuff 1. Counting the User records which don't have a relationship with ModelB. I managed to do that using : ModelB.objects.all().annotate(user_count=User.objects.count()-Count('user')) It works but feels like a hack. Is there a better way to do this (while still using annotate()) ? 2. With filtering I modified my previous query to be filtered with the currently logged in User so I can display custom content for each user. I intended to keep the same user_count value regardless of the logged in user: ModelB.objects.filter( user=request.user ).annotate( user_count=User.objects.count()-Count('user') ) I get user_count = User.objects.count() - 1 in every case. What I understand is that filtering on ModelB.user restricts Count('user') output. Is there a workaround for this ? Thanks for helping ! -
How to upload images and use image as background image on blog post?
Okay so I want to be able to upload an image when I am writing a blog entry in the add post section of the admin panel and use that image as the background image of a link to that post. The anchor link is on the homepage. What field type would be best for this? Do I need to write an extra view? blog/urls.py: from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.post_list, name='post_list'), url(r'^post/(?P<pk>\d+)/$', views.post_detail, name='post_detail'), ] blog/views.py from django.shortcuts import render, get_object_or_404 from django.utils import timezone from .models import Post def post_list(request): posts = Post.objects.filter(published_date__lte=timezone.now()).order_by('published_date') return render(request, "blog/post_list.html", {"posts": posts}) def post_detail(request, pk): post = get_object_or_404(Post, pk=pk) return render(request, 'blog/post_detail.html', {'post': post}) blog/models.py from django.db import models from django.utils import timezone class Post(models.Model): author = models.ForeignKey('auth.User') title = models.CharField(max_length=200) text = models.TextField() created_date = models.DateTimeField( default=timezone.now) published_date = models.DateTimeField( blank=True, null=True) def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.title -
Mapping a Legacy Database
I am attempting to map the tables of a legacy Oracle database using Django's ORM. Unfortunately, rather than using a transaction log, this legacy database tracks changes by inserting a new row with the updated information and an identical primary key with a column called change_indicator set to NULL. The old row's change_indicator column is set to a letter code indicating what was changed. I am only interested in mapping the most up to date row, that is the ones with change_indicator set to NULL. How ought I to go about this? My current solution is to attach a filter to the query set which enforces this constraint: class IdentityManager(models.Manager): """ Filter out historic entries in the Identity table """ def get_queryset(self): return super(IdentityManager, self).get_queryset().filter(change_indicator=None) This is fine if I'm just querying using Identity.objects.filter(...) and the like, but I need to set up a one to one relationship with it and another table. That looks like: class Person(Identity): class Meta: db_table = 'person' managed = False _person_pidm = models.OneToOneField('Identity', parent_link=True, to_field="_pidm_identity", db_column="person_pidm", primary_key=True) # Other fields etc When I query on Person for a specific pk I get multiple results back, one for each Identity object with that pk. The … -
Could ForeignKey feild link diffirent type Models in Django?
I need to use Django to achieve somethign like a tree, node in this tree has a single parent, and many children.The problem is that the type of the nodes are not the same, they belong to different Model, although they all have one foreign keys named parent, but different in other fields and methods, and each node's parent is likely to be any other types of nodes.for a node, I want to know who is its parent and who is its childs.This drives me crazy, anyone can help me? -
Django Rest Framework: how to set a custom name form non_field_errors?
I'm validating if user that is registering on my website is giving me unique address (city, street, street number etc.) and when it's not unique, then I'm raising serializers.ValidationError: class UserSerializer(serializers.ModelSerializer): def validate(self, attrs): city = attrs['city'] street = attrs['street'] street_number = attrs['street_number'] apartment_number = attrs['apartment_number'] if 'apartment_number' in attrs else None unique = check_address_unique(city, street, street_number, apartment_number) if not unique: raise serializers.ValidationError(_('Another user has already been registered under this address.')) return attrs The problem is that the field name under which the error is passed is this standard non_field_errors: {"non_field_errors":["Another user has already been registered under this address."]} I'd like to somehow give this error a custom name, so the desired output would be: {"address":["Another user has already been registered under this address."]} How to accomplish that? -
In Django, my urls "stick" and they keep the value from a specific page :(
I have a template with this line:< a href="objMod/{{item.id}}" type="submit" class="btn btn-primary">Edit' It passes the parameter ok, but then every single url in the system attaches it to the url. For example /objReg/ObjMod/6/ or /index/objMod/6 even when they don't have any parameters in their template. Please help. Thank you -
Django and Angular 2 templateUrl
I'm desided to integrate existing angular 2 app in my Dgango REST project. 1)create Django app with static folder for my frontend: urls.py: from django.conf.urls import url from frontend import views from django.conf import settings from django.conf.urls.static import static urlpatterns = [ url(r'^$', views.index, name='index'), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) views.py: from django.shortcuts import render def index(request): """ Renders the Angular2 SPA """ return render(request, template_name='index.html') 2)move my angular 2 app in fronted static folder 3)add static settings in my settings: STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'frontend', 'static'), ] STATIC_ROOT = os.path.join(BASE_DIR, 'static') 4)make changes in index.html: <html> <head> <base href="/"> <title>PhotoHub</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> {% load staticfiles %} <link rel="stylesheet" href="{% static "node_modules/bootstrap/dist/css/bootstrap.min.css" %}"> <link href="{% static "bower_components/font-awesome/css/font-awesome.min.css" %}" rel="stylesheet" /> <link href="{% static "bower_components/alertify.js/themes/alertify.core.css" %}" rel="stylesheet" /> <link href="{% static "bower_components/alertify.js/themes/alertify.bootstrap.css" %}" rel="stylesheet" /> <link rel="stylesheet" href="{% static "styles.css" %}"> <script src="{% static "bower_components/jquery/dist/jquery.min.js" %}"></script> <script src="{% static "node_modules/bootstrap/dist/js/bootstrap.min.js" %}"></script> <script src="{% static "bower_components/alertify.js/lib/alertify.min.js" %}"></script> <!-- 1. Load libraries --> <!-- Polyfill(s) for older browsers --> <script src="{% static "node_modules/core-js/client/shim.min.js" %}"></script> <script src="{% static "node_modules/zone.js/dist/zone.js" %}"></script> <script src="{% static "node_modules/reflect-metadata/Reflect.js" %}"></script> <script src="{% static "node_modules/systemjs/dist/system.src.js" %}"></script> <!-- 2. Configure SystemJS --> <script src="{% static … -
Field doesn't have a default value despite it doesn't even exists
I get such warning despite this field was deleted previously. Field 'how_much_new_notifications' doesn't have a default value") -
Django - server code response in JsonResponse
Is it possible to add server response code to JsonResponse ? I need server to reply with 404 in some circumstances. I have following view def CreateOrAuth(request): try: username = request.POST.get("username") queryset = User.objects.get(username=username) except Exception as e: return JsonResponse({'status': 'user with {} not exist'.format(username)}) And I want to add 404 server code here -
Python Get User Fullname From Foreign Key Customer
i want to get the customer fullname, but in the end i only get the id. orders = Order.objects.filter(restaurant=request.user.restaurant).order_by('customer__id').values('customer__id', 'customer__address', 'customer__avatar', 'customer').annotate(total_order= Count('customer__id')) in value('customer') i want get the customer fullname but i only get the id. from django.contrib.auth.models import User class Customer(models.Model): user = models.OneToOneField(User, on_delete= models.CASCADE, related_name= 'customer') avatar = models.CharField(max_length= 500) phone = models.CharField(max_length= 500, blank= True) address = models.CharField(max_length= 500, blank= True) def __str__(self): return self.user.get_full_name() thanks. -
Django app with user authentication at project level
How do I handle user authentication inside an app when the authentication of users is handled at project level? Im building an app where I need an authenticated user object when creating database entries, but I don't want to deal with the whole signup/sign-in logic inside the app, that should be delt with at a project level instead. The app requires a user being signed in, but when developing I can't figure out where to put this. Can I "fake" an authenticated user inside the settings.py for the project? -
Django all-auth set password to social account manually
Is it possible to alter the process of creating password for social account ? I want some how to set password myself to local accounts that attached to social ones. -
Django: Model._meta in databaserouter is auth
Well i have a big problem. I started recently to work in a little api in Django Rest Framework. Well I have 2 databases to access, and for that i use a snippet I found in this page. This is the snippet: class ModelDatabaseRouter(object): """Allows each model to set its own destiny""" def db_for_read(self, model, **hints): # Specify target database with field in_db in model's Meta class print (model._meta) if hasattr(model._meta, 'in_db'): print (model._meta.in_db) return model._meta.in_db return None def db_for_write(self, model, **hints): # Specify target database with field in_db in model's Meta class print (model._meta) if hasattr(model._meta, 'in_db'): print (model._meta.in_db) return model._meta.in_db return None def allow_syncdb(self, db, model): # Specify target database with field in_db in model's Meta class print (model._meta) if hasattr(model._meta, 'in_db'): print (model._meta.in_db) if model._meta.in_db == db: return True else: return False else: # Random models that don't specify a database can only go to 'default' if db == 'default': return True else: return False # <<< (The print is for debug reasons, the 'in_db' propertie was added in settings.py) When I do the migrate command after makemigrations for my app. This is the debug in console: Operations to perform: Apply all migrations: admin, auth, backendSami, contenttypes, … -
model convert field automatically?
Who can I have a model which can save date in database in Greogorian but get and show in Jalali. The jdatetime is very good but django_jalali which uses jdatetime for django is not a cool one and has poor documentation. so I just want to use jdatetime. with jdatetime I can convert dates. from jdatetime import date as jdate from datetime import date #get jalali date from gregorian jd = jdate.fromgregorian(date=date.today()) #get gregorian date from jalali gd = jd.togregorian() I should get dates in Forms. using commit=False is good Idea but what if I use FormModel? -
How to combine fields of two different model and create ModelSerializer
I have two models CustomUser and UserProfile. class CustomUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('email address'), max_length=254, unique=True, blank=True) first_name = models.CharField(_('first name'), max_length=30, blank=True) last_name = models.CharField(_('last name'), max_length=30, blank=True) class UserProfile(models.Model): user = models.OneToOneField(CustomUser, on_delete=models.CASCADE) owner_of = models.CharField(max_length=100, blank=True) total_years= models.CharField(_('In Current Profession Since'),max_length=100,blank=True, null=True) serializers.py: class AccountSerializer(serializers.ModelSerializer): class Meta: model = CustomUser fields = ('id', 'email','first_name', 'last_name',) class ProfileSerializer(serializers.ModelSerializer): user = AccountSerializer(read_only=True,required=False) class Meta: model = UserProfile fields = ('user','owner_of','total_years','first_name','last_name','email') Error I get "Field name first_name is not valid for model UserProfile." How to combine two model fields and make create and update function -
Threading database issues in celery tasks using eventlet
I have a project under dev VM 'ubuntu/trusty'. I use virtualenv with the following packages: celery 3.1.23 eventlet 0.18.4 django 1.8.15 Python version is 3.4.3. I use supervisor with eventlet as a worker for run some services and celery tasks among them. This is the part of the supervisor's configuration: [program:celery-worker-default] command=/home/vagrant/.virtualenvs/meridian/bin/python /vagrant/meridian/meridian/manage.py celery worker --loglevel=INFO -P eventlet -c 3 -Q default -E -n default.queue directory=/vagrant/meridian/meridian user=vagrant autostart=true autorestart=true stdout_logfile=/var/log/supervisor/celery-worker-default-stdout.log stderr_logfile=/var/log/supervisor/celery-worker-default-stderr.log priority=999 stdout_logfile_maxbytes=10MB stdout_logfile_backups=5 stderr_logfile_maxbytes=10MB stderr_logfile_backups=5 When tasks are running they fail with the following stack trace: Traceback (most recent call last): File "/home/vagrant/.virtualenvs/meridian/lib/python3.4/site-packages/celery/app/trace.py", line 231, in trace_task loader_task_init(uuid, task) File "/home/vagrant/.virtualenvs/meridian/lib/python3.4/site-packages/djcelery/loaders.py", line 114, in on_task_init self.close_database() File "/home/vagrant/.virtualenvs/meridian/lib/python3.4/site-packages/djcelery/loaders.py", line 85, in close_database return self._close_database() File "/home/vagrant/.virtualenvs/meridian/lib/python3.4/site-packages/djcelery/loaders.py", line 76, in _close_database close() File "/home/vagrant/.virtualenvs/meridian/lib/python3.4/site-packages/django/db/__init__.py", line 64, in close_old_connections conn.close_if_unusable_or_obsolete() File "/home/vagrant/.virtualenvs/meridian/lib/python3.4/site-packages/django/db/backends/base/base.py", line 403, in close_if_unusable_or_obsolete self.close() File "/home/vagrant/.virtualenvs/meridian/lib/python3.4/site-packages/django/db/backends/base/base.py", line 191, in close self.validate_thread_sharing() File "/home/vagrant/.virtualenvs/meridian/lib/python3.4/site-packages/django/db/backends/base/base.py", line 421, in validate_thread_sharing % (self.alias, self._thread_ident, thread.get_ident())) django.db.utils.DatabaseError: DatabaseWrapper objects created in a thread can only be used in that same thread. The object with alias 'default' was created in thread id 140089123953704 and this is thread id 140088751748512. Any task that contains DB operations fails. I tried to use select_for_update() and with atomic(): … -
Why do so many people use NodeJs as Backend instead of Python?
Checking out some Hackathons, Django/Python is almost non-existent in terms of usage for a backend. Example Example The list keeps going. Nobody is seeming to use Python for backend, but many people say Python > Node JS? What does Node JS have that people are inspired to use that instead of Python in these events (hackathons).. -
DionaeaFR error, cannot import name patterns
I had problem when run python manage.py 0.0.0.0:8000 Unhandled exception in thread started by Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/django/utils/autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/django/core/management/commands/r unserver.py", line 121, in inner_run self.check(display_num_errors=True) File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 374, in check include_deployment_checks=include_deployment_checks, File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 361, in _run_checks return checks.run_checks(**kwargs) File "/usr/local/lib/python2.7/dist-packages/django/core/checks/registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "/usr/local/lib/python2.7/dist-packages/django/core/checks/urls.py", line 14, in check_url_config return check_resolver(resolver) File "/usr/local/lib/python2.7/dist-packages/django/core/checks/urls.py", line 24, in check_resolver for pattern in resolver.url_patterns: File "/usr/local/lib/python2.7/dist-packages/django/utils/functional.py", line 35, in get res = instance.dict[self.name] = self.func(instance) File "/usr/local/lib/python2.7/dist-packages/django/urls/resolvers.py", line 3 13, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/usr/local/lib/python2.7/dist-packages/django/utils/functional.py", line 35, in get res = instance.dict[self.name] = self.func(instance) File "/usr/local/lib/python2.7/dist-packages/django/urls/resolvers.py", line 3 06, in urlconf_module return import_module(self.urlconf_name) File "/usr/lib/python2.7/importlib/init.py", line 37, in import_module import(name) File "/opt/DionaeaFR/DionaeaFR/urls.py", line 1, in from django.conf.urls import patterns, url ImportError: cannot import name patterns Could someone help me? What should i do? -
Is it better to combine model subclasses and have un-used fields, or create concrete subclasses?
I'm writing an app in Django and I have an instance where I would like to create a model with a single layer of inheritance to a number of sub classes. i.e: Vehicles -> Cars, Bikes, Busses I need to be able to search and store items as the Vehicle superclass, but the downcast to the subclass to use additional fields in most cases. In Django, this will cause a lot of hits to the database to retrieve sub-models, or a massive join and query. Should I use the concrete subclasses and take the performance hit, or should I add the extra fields to one vehicle model and then have unused fields in various objects? I should note that the additional fields are typically 1-3 fields of small size i.e. Char strings, and that a total of 4 subclasses (max 9 unused fields per model) -
Perform operation with different users
I am developing a file manager in Django using Python 3.5.2. I need to manage files that are owned by different Linux user, but each user do not have any permission to read other users' files. I have tried to develop a root daemon process that only accept commands from main application and cannot be accessed directly. The daemon uses os.fork() to start a new child that will perform seteuid() and setguid(), then perform file manager operation. However, I do not have much success in dealing with forked child. What I need is I am able to run commands under different users with seteuid() and setguid(), so that each users can manage their own files properly. The following are my code in Django: Main App views.py def file_operation(request): user = { 'username': request.session.get("username"), 'home_dir': request.session.get('home_dir'), 'uid': request.session.get("uid"), 'gid': request.session.get("gid") } url = u'%s:%s/files?username=%s&home_dir=%s&uid=%s&gid=%s' % ( settings.DAEMON_FILE_HOST, settings.DAEMON_FILE_PORT, user['username'], user['home_dir'], user['uid'], user['gid'] ) return ProxyRequest().proxy_view(request, url) ProxyRequest() is a custom class that pass all the request from Main App to another url (daemon) and retrieve the response. Daemon views.py def connector(request): user = { 'username': request.GET.get("username"), 'home_dir': request.GET.get('home_dir'), 'uid': int(request.GET.get("uid")), 'gid': int(request.GET.get("gid")) } newpid = os.fork() response = None if newpid … -
Django JSONField string containment
Using Django 1.10's JSONField, i want to filter queryset by the json field that have a value at specific key that contains a sub string (sql like). e.g. there is a json field link, with the url key. i want the objects that it's url contains .jpg -
How to use gulp browser sync with django apps served by apache mod_wsgi?
gulp runs browser sync on a test server that only serves static web pages (html, css, sass,...). Is there a way to use browser sync or a similar module to inject changes (css changes) live to the browser on an apache server serving django with the mod_wsgi module? -
how to stack images from bottom up in Django
I'm starting with this code: {% for award in data.profile.awards %} <img src="media/{{ award.Medals.ribbon }}"> {% if forloop.counter|divisibleby:3 %} <br /> {% endif %} {% endfor %} my problem is that it goes from top down. Meaning that it produces the first three, then a break, then another three, and repeat from there. What I need is to go from bottom up. in my case, If there's 4 images, I want 1 on top, and 3 on bottom. If there's 8, then there's 2 on top, 3 in the middle, then 3 on bottom. How do I do that? Thanks. -
i cannot connect django with postgresql
i created my project and installed postgresql with a user called myprojectuser with password 'secret' and i create my database called myproject, then i configured in my project of django with the username: myprojectuser with password secret, but i was trying to run my migrations but displayed these errors. http://pastebin.com/8wgY0qMJ How can i fix it? i changed in my /etc/postgresql/9.5/main/pg_hba.conf local all postgres md5 and ran sudo servic