Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Get the set of objects from Many To One relationship two levels deep
I have 3 models and I'd like to get the set of all related object from the 3rd model given the 1st model. For example: Clas Dealer(models.Model): .. class Make(models.Model): dealer = models.ForeignKey(Dealer) .. Class Model(models.Model): Make = models.ForeignKey(Make) .. How would I go about getting all of the related Model objects given the Dealer? The Dealer object is getting passed in the form of kwargs['instance'] -
Django REST - adding custom fields to request.data in case of array of objects
I have a Django 1.9 project and a REST view which receives from client-side a list objects, so the code looks like this: Client-side object: [ { "field_a": "...", "field_b": "..." }, { "field_a": "...", "field_b": "..." } ] The view: @api_view(['POST']) def send_sim_info(request): serializer = MySerializer(data=request.data, many=True) So the serializer is of type ListSerializer QUESTION: How do I add fields to request.data in this case? In one object case, I would just write request.data['addition_field'] = my_value. What is the cleanest way to do a similar trick for the case of array? -
Converting postgresql indexes to Django migrations
We have a Django application that has been in production since Django 1.1. Over the years, we've manually added bells and whistles to the production PostgreSQL db that weren't at the time overtly supported by Django's db automation, especially in the form of custom indexes. Django's come a long way since 1.1, and now w/ 1.10 I'm pretty sure the migration framework supports all the custom features we've added manually. Is there any automated tool which will compare a database to the models, and generate migrations to bring the models up to date with the db? -
Django i18n_patterns without trailing slash
I'm trying to get rid of trailing slash from urls. Currently the web-server successfully removes slashes and APPEND_SLASH = false Everything works fine but I have a problem with the localized homepage: http://example.com/en/ - ok http://example.com/en - Page not found (404) Django tried these URL patterns, in this order: ^admin/ ^en/ The current URL, en, didn't match any of these. This is my urls.py settings: urlpatterns = [ url(r'^admin/', admin.site.urls), ] urlpatterns += i18n_patterns( url(r'^$', views.index, name='index'), ) It it possible to make these i18n_patterns work without slashes? -
django-allauth getting Sorry, something went wrong. We're working on getting this fixed as soon as we can
I am getting this error by using django-allauth, I have put ** http://localhost:8000** and http://www.localhost:8000 as Valid OAuth redirect URIs in Facebook login. And here is the Facebook part of the setting.py AUTHENTICATION_BACKENDS = ( # Needed to login by username in Django admin, regardless of `allauth` 'django.contrib.auth.backends.ModelBackend', # `allauth` specific authentication methods, such as login by e-mail 'allauth.account.auth_backends.AuthenticationBackend', ) LOGIN_REDIRECT_URL = '/' SOCIALACCOUNT_QUERY_EMAIL = True SOCIALACCOUNT_PROVIDERS = { 'facebook': { 'SCOPE': ['id' ,'email', 'name','local', 'gender' ], 'METHOD': 'js_sdk' # instead of 'oauth2' } } # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.facebook', ] and I have added client_id and secret in the database, first time I used Facebook login, it process me to my facebook page, then I hit the back button to my web app login page, after that I couldn't be able to use facebook login anymore, it always show "Sorry, something went wrong. We're working on getting this fixed as soon as we can." No matter which browser I use( include incognito window). Anyone had the same problem? Has Facebook block my IP? -
Is posible have two model in Custom Auth in Django?
I have two models User and Clientes, the first one is works perfectly but now I need that Clientes can access to my system but as you django just allow one model in the AUTH_USER_MODEL. This is my model User class User(AbstractUser): direccion = models.CharField(max_length=255) telefono = models.CharField(max_length=50) id_perfil = models.ForeignKey(Perfil, on_delete=models.CASCADE) fecha_modificacion = models.DateTimeField(null=True) fecha_cancelacion = models.DateTimeField(null=True) This is my model Clientes class Cliente(models.Model): id_cliente = models.AutoField(primary_key=True) nombres = models.CharField(max_length=255) apellidos = models.CharField(max_length=255) usuario = models.CharField(max_length=100) password = models.CharField(max_length=255, null=True ,blank=True ) correo_electronico = models.EmailField() direccion = models.TextField() telefono = models.CharField(max_length=20) telefono_celular = models.CharField(max_length=20) status = models.IntegerField() This is my cutom Auth class CustomUserAuth(object): def authenticate(self, username=None, password=None): try: user = User.objects.get(username=username) if user.check_password(password): return user except User.DoesNotExist: return None def get_user(self, user_id): try: user = User.objects.get(pk=user_id) if user.is_active: return user return None except User.DoesNotExist: return None both models have user and password so I want that the Login system in django can identify if is User or Cliente, How can I do that? In my settings AUTH_USER_MODEL = 'backend.User' AUTHENTICATION_BACKENDS = ('apps.backend.backends.CustomUserAuth',) -
Django: How to save database connection
I have a postgresql database with a table with almost 2000 rows. Client loads the first 75 rows, and when the user scrolls down the client loads another 75. My task is to optimise loading of additional data. There are 3 queries to actually retrieve the data. 2 of them take 50 ms each, and the other one takes 150ms, which adds up to total of 250ms, whereas the actual time python code gets executed is 600ms. I measured execution of each query and then printed the queries. I noticed that the first query takes additional 350ms to execute, but connection.queries says that it took the query 50ms. I removed the first query (substituted it with a dummy) and noticed that now the time is 550ms and the second query takes additional 350ms. I added the first query back and substituted it with raw sql like this. cursor = connection.cursor() t_count_query = time.time() cursor.execute('...') result = cursor.fetchone()[0] # the result of this query is a single value Instead of one line I now have connection.cursor() and then the actual query. I dicided to time them separatly with this code t_connecting = time.time() cursor = connection.cursor() t_connecting = time.time() - t_connecting … -
django and jquery datatables
I am using django to build a database that can be viewed over a website. Before going deep into my project, I built the django app and added a table into my models with only one row of data. Now I am trying to visualise that table using jquery datatables. However, jquery datatables format is not showing. I tried every possible solution I found but nothing is working out yet. Models.py from django.db import models class Variant(models.Model): type = models.CharField(max_length = 20) protein_id = models.CharField(max_length = 20) gene_symbol = models.CharField(max_length = 20) chromosome = models.CharField(max_length = 5) position = models.CharField(max_length = 20) variation = models.CharField(max_length = 20) consequence = models.CharField(max_length = 40) rs = models.CharField(max_length = 20) maf = models.CharField(max_length = 20) phenotype = models.CharField(max_length = 20) source = models.CharField(max_length = 40) Views.py from django.shortcuts import render from view_data.models import * def variants(request): queryset = Variant.objects.all() return render(request, "variants.html", {"allvars": queryset}) Urls.py from django.conf.urls import url from django.contrib import admin from view_data import views from django.conf import settings from django.conf.urls.static import static urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^variants/', views.variants), ] if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) variants.html {% load static %} <html> <head> <script src="{{ STATIC_URL }} js/jquery.js"></script> <script src="{{ … -
PyCharm - External documentaion URL/Path pattern (Django)
Does any one here have the URL/Path pattern for setting up external Django documentation in PyCharm? Thanks. -
Unexpected identifier when accessing django variable in jquery
I'm just trying to set a variable in jquery so I can change some html and I'm getting the following error: (index):208 Uncaught SyntaxError: Unexpected identifier I have checked everything a lot, I have a feeling it will just be an infuriating typo somewhere but I need help I can't stare at it any longer. Here is my jquery: <script> // make this document specific and move to another file...? $( document ).ready(function() { //set some variables e.g. var1 = 5; for ( var i = 0; i < var1; i++ ) { // do things var2 = 1; var3 = 10; for ( var j = var2; j <= var3; j++) { //more stuff } var change_start = $('td').filter(function() { return Number(this.textContent) == var2; }); ///This line is raising an error!!! var the_person = {{ person }}; var add_name = change_start.prepend('<a href="#"><center>'+the_person+'</center></a>'); } }); </script> I've taken a lot out so it's easy to look at. The script worked just fine until I added the last 3 lines so it must be there. For now this script is in the html document, I plan to move it later. I pass person to the template in the view that renders … -
Django admin site without CSS
I've used by error the command "./manage collectstatic" and now my admin site is completly awful. How I can fix that? Thanks. -
Access child model class attributes in multi table inheritance in Django
I'm trying to iterate over child model instances' attributes in a template, specifically only the childs attributes. So far using django-model-utils I've been able to return the sub-class instead the parent, but when I access the attributes I get both the parents and the childs: class Product(models.Model): created_at = models.DateTimeField(default=timezone.now) updated_at = models.DateTimeField(auto_now=True) name = models.CharField(...) objects = InheritanceManager() def attrs(self): for attr, value in self.__dict__.iteritems(): yield attr, value class Vacuum(Product): power = models.DecimalField(...) class Toaster(Product): weight = models.DecimalField(...) views.py def product_detail(request, slug): product = Product.objects.get_subclass(slug=slug) template {% for name, value in product.attrs %} <td>{{ name }}</td> <td>{{ value }}</td> {% endfor %} -
Celery error: kombu.exceptions.NotBoundError: Can't call method on Exchange not bound to a channel
I'm using celery 4.0.2 with rabbitmq 3.6.6 and Django 1.10, here is my configuration: from django.conf import settings os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'fidecom.settings') app = Celery('my_app') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) app.conf.BROKER_URL = 'amqp://{}:{}@{}'.format(settings.AMQP_USER, settings.AMQP_PASSWORD, settings.AMQP_HOST) app.conf.CELERY_DEFAULT_EXCHANGE = 'my_app.celery' app.conf.CELERY_DEFAULT_QUEUE = 'my_app.celery_default' app.conf.CELERY_TASK_SERIALIZER = 'json' app.conf.CELERY_ACCEPT_CONTENT = ['json'] app.conf.CELERY_IGNORE_RESULT = True app.conf.CELERY_DISABLE_RATE_LIMITS = True app.conf.BROKER_POOL_LIMIT = 2 app.conf.CELERY_QUEUES = ( Queue(settings.QUEUE_1), Queue(settings.QUEUE_2), Queue(settings.QUEUE_3), ) It works fine, but when I try to add a new queue, ie app.conf.CELERY_QUEUES = ( Queue(settings.QUEUE_1), Queue(settings.QUEUE_2), Queue(settings.QUEUE_3), Queue(settings.QUEUE_4), ) I get this error: kombu.exceptions.NotBoundError: Can't call method on Exchange not bound to a channel If I remove one of these queues, it works again, so it seems to be limited to 3 queues. I don't understand why. Celery is launched like this: celery worker -A my_app.celery_app Any idea? Thanks in advance! -
HEROKU Error opening data file /app/vendor/tesseract-ocr/tessdata/eng.traineddata
I have a Django app which is deployed in Heroku. I'm trying to read text from image using pytesseract .I can run this app in localhost without problem but in heroku its showing an error Error opening data file /app/vendor/tesseract-ocr/tessdata/eng.traineddata even after I added pytesseract buildpacks as mentioned here def ocr(serializer): imgObject = ImageModel.objects.get(id=serializer.data['id']) imgPath = (os.path.join(settings.MEDIA_ROOT, imgObject.image.name)) InputFile = str(imgPath).replace("\\", "/") pytesseract.pytesseract.tesseract_cmd = 'C:/Program Files (x86)/Tesseract-OCR/tesseract' return pytesseract.image_to_string(Image.open(InputFile)) -
Django - Internal Updates to Databases
Django - what is the best way to internally update database values - through an API built for internal uses only or through standard database operations. Please help. I am new to Django and using Django-Rest-Framework for the APIs. -
Django-RQ : How to log each rq-worker to a different file
Is it possible to have each django rq-worker log to a different file, with rollover and max-file-size policy? Thank you -
Django Postgresql droping column defaults at migrate
i'm facing an issue with defaults values of tables. for example i have this model: class model1(models.Model): field1 = models.CharField(max_length=50, default='My Default Value 1',db_column='field1') field2 = models.CharField(max_length=10) class Meta: db_table = 'model1' and the postgresql table is generated without the default: mydb=# \d model1 Table "public.model1" Column | Type | Modifiers --------+-----------------------+----------------------------------------------------- id | integer | not null default nextval('model1_id_seq'::regclass) field1 | character varying(50) | not null field2 | character varying(10) | not null Indexes: "model1_pkey" PRIMARY KEY, btree (id) the output of migrate sqlmigrate is: CREATE TABLE "model1" ("id" serial NOT NULL PRIMARY KEY, "field1" varchar(50) NOT NULL, "field2" varchar(10) NOT NULL); COMMIT; but if i modify the default value in the model and run a makemigrations/migrate and after that i look into sqlmigrations the output genereates a weird DROP DEFAULT after creating ALTER TABLE "model1" ALTER COLUMN "field1" SET DEFAULT 'My Default Value 1 modified'; ALTER TABLE "model1" ALTER COLUMN "field1" DROP DEFAULT; COMMIT; is there something i am missing or default values for columns are just not supported ?? Thanks in advance -
Coverage misses Django model tests
I have this model: class Manager(models.Model): """ This model defines a manager. If a User has a Manager record, the User is a manager. """ user = models.OneToOneField('users.User', on_delete=models.PROTECT) static_name = models.CharField(max_length=100) def __str__(self): return 'Manager {}'.format(self.static_name) class Meta: ordering = ('static_name',) default_permissions = ['index', 'manage'] def save(self, *args, **kwargs): """ The save method is overwritten to perform a safety check: a patient should never be made a manager. """ if self.user.is_patient or self.user.has_coupled_patient: raise ValueError('Een patiënt mag geen manager gemaakt worden.') super(Manager, self).save(*args, **kwargs) With these tests: class ManagerTest(TestCase): def setUp(self): user1 = User.objects.create(first_name='User', last_name='One', email='user@user.com', password='test') user2 = User.objects.create(first_name='User', last_name='with Patient', email='user2@user.com', password='test') pharmacy = Pharmacy.objects.create(vidivici_id='2511', name='Pharmacy 1', address='Test', opening_hours='Test') couple_request1 = UserPatientCoupleRequest.objects.create(user=user2, couple_last_name='with Patient', couple_sex='M', couple_DOB='1980-01-01', couple_BSN=123456789, couple_pharmacy=pharmacy) patient1 = Patient.objects.create(vidivici_id='25110001', first_name='Patient', last_name='One', sex='M', DOB='1980-01-01', BSN=123456789, pharmacy=pharmacy) def test_manager_str(self): user = User.objects.get(email='user@user.com') manager = Manager.objects.create(user=user, static_name='Manager 1') self.assertEqual(str(manager), 'Manager {}'.format(manager.static_name)) def test_manager_save_with_patient(self): user_with_patient = User.objects.get(email='user2@user.com') patient = Patient.objects.get(vidivici_id='25110001') couple_request = UserPatientCoupleRequest.objects.get(user=user_with_patient) UserPatient.objects.create(user=user_with_patient, patient=patient, couple_request=couple_request) with self.assertRaises(ValueError): Manager.objects.create(user=user_with_patient, static_name=user_with_patient.get_full_name()) The tests both pass, but coverage still tells me the __str__ and save methods are not covered. What am I doing wrong? I'm using Django 1.11b1 on Python 3.6. I'm a beginner at testing so it's probably something obvious. -
Django: css file not loading (404)
The css file shows a 404 on chrome developer tool although I specified to where my css file is and is also available. html: {% load static %} <!DOCTYPE html> <html lang="en"> <head> .... <title>title!</title> .... <link rel="stylesheet" type="text/css" href="{% static 'css/base.css' %}" /> </head> <body> .... settings.py : INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'meme', ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')] , 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'meme/media/') urls.py :- urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^', include("meme.urls", namespace='memes')), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Can anyone help me out? Would really appreciate any help. Thanks in advance. -
django static file loading adds a non-existent directory to the file path
I have a Django project which has the following settings for loading static files: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'proj.apps.ProjConfig', ] STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = os.path.join(BASE_DIR, 'static/') STATICFILES_DIRS = [ os.path.join(BASE_DIR, "images/"), ] LOGIN_REDIRECT_URL = 'login' My urls.py is defined as: from django.conf.urls import url from django.contrib.staticfiles.urls import staticfiles_urlpatterns from django.contrib import admin from django.contrib.auth import views as auth_views from proj import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', views.index, name='index'), url(r'^login/$', auth_views.login, {'template_name': 'login.html'}, name='login'), url(r'^logout/$', auth_views.logout, name='logout'), ] + staticfiles_urlpatterns() I have a file called logo.png which is copied to the satic directory when I run python manage.py collectstatic as expected. My template for login (login.html) attempts to load this file as follows: {% extends 'base.html' %} {% block title %}Login{% endblock %} {% block content %} {% load static %} <img src="{% static "logo.png" %}" alt="My image"/> <h2>Login</h2> <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Login</button> </form> {% endblock %} Now the image is not loaded and the error comes with: Not Found: /login/logo.png I am not sure why it prepends the /login/ directory to the path and I have been trying to figure this out for hours … -
How to get logged in user id in Django
I am very new in Python and Django. A am trying to make app but I have an issue. Can anyone help me, please xD I can't get id of authenticated user... I tried it in this way, and many other ways... views.py class CreateProfile(CreateView): template_name = 'layout/add_photo.html' model = Profile user = Profile.user fields = ['image', 'user'] success_url = reverse_lazy('git_project:user_profile') html <form class="form-horizontal" action="" method="post" enctype="multipart/form-data"> {% csrf_token %} {% include 'layout/form_template.html' %} <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <button type="submit" class="btn btn-success">Save Changes</button> </div> </div> And when i'm starting app, and want to change/add picture, I can do it for anyone from my database, not only for logged in user. enter image description here Thanks for patience and help! -
Django pagination on a model with foreignkey
I have two django models Calculations and Customers. The Calculations model has user as ForeignKey, but the user can be empty. The view is as follows : def archive(request): calculations = Calculations.objects.filter(user=request.user) calculation_data = [] for calculation in calculations: customer_fullname, car_chassis, car_registration = ('', '', '') if calculation.customer_id is not None: customer = Customer.objects.get(id=calculation.customer_id) customer_fullname = '{} {}'.format(customer.firstname, customer.lastname) car_chassis = customer.chassis car_registration = customer.registration calculation_data.append({ 'calculation': calculation, 'price': price_incl_vat(calculation.purchase_price), 'customer_fullname': customer_fullname, 'car_chassis': car_chassis, 'car_registration': car_registration, }) context = {'calculation_data': calculation_data} return render(request, 'master/archive.html', context) And in archive.html I loop through calculation_data as follows : {% for calculation in calculation_data %} ..... ..... {% endif %} And everything works fine. Now I want to implement pagination. According to docs it can be done as : calculations = Calculations.objects.all() paginator = Paginator(calculations, 25) But how can I implement pagination to my calculation_data? Because there is stored all the data through which I loop in the template. Of is there an better way to write the query to be able to accomplish pagination? Thanks in advance. -
Error 413 on posts using Requests in celery task
I do a post using the Requests framework on a worker thread (Celery with RabbitMQ as broker). It works fine most of the time but occasionally i get a 413 (request body too large error). I have set the client_max_body_size in nginx to 50M, and restarted nginx but the issue persists (the max post size is about 3MB). (2 nginx conf file content shown below). Any ideas how to fix would be greatly appreciated please. Stack Python 2.7.6 Django 1.8.5 Ubuntu 14.04.3 LTS Celery, RabbitMQ, nginx nginx.conf user www-data; worker_processes 4; pid /run/nginx.pid; events { worker_connections 768; # multi_accept on; } http { sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 65; types_hash_max_size 2048; include /etc/nginx/mime.types; default_type application/octet-stream; access_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log; gzip on; gzip_disable "msie6"; include /etc/nginx/sites-enabled/*; client_max_body_size 50M; } Contents of sites-enabled server { listen 80; server_name www.***.com; client_max_body_size 50M; location /static/ { client_max_body_size 50M; root /home/project/jt-server; } location / { client_max_body_size 50M; include proxy_params; proxy_pass http://unix:/home/project/jt-server/jt.sock; } } -
how to stop / kill and start a process in aws ebs using .ebextensions ?
I have tried using the following .ebextensions : commands: 01-kill: command: "kill $(pgrep -flvx auto_pilot.py | grep auto_pilot.py)" ignoreErrors: true 02-wget: command: "python /opt/python/current/app/phoenix_app/auto_pilot.py &" -
How to override Django admin templates 1.10
I am trying to override the default admin template in django 1.10 what i have done so far is i have created templates directory at same level where manage.py reside and inside templates i created admin folder and then base_site.html but it is not working. i have searched django 1.10 docs but unable to find any information about overriding default admin templates templates/admin/base_site.html myapp --myapp ----settings.py --accountapp --blogapp --templates ----admin ------base_site.html my setting.py is INSTALLED_APPS = [ 'shrines', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework.authtoken' ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ 'templates', ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ]