Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: how to call "contains" function in a template
I need to know how to use contains in a Django template. I want to do something like this: In view: my_query = MyClass.objects.filter(key=value).my_var And in a template like: {% if my_query contains 'X' %} <p>My var contains an X</p> {% endif %} {% if my_query contains 'Y' %} <p>My var contains a Y</p> {% endif %} Other way I already know would be by validating in view: my_query_X = MyClass.objects.filter(my_var__contains='X').exists() my_query_Y = MyClass.objects.filter(my_var__contains='Y').exists() Then in template: {% if my_query_x == True %} <p>My var contains an X</p> {% endif %} {% if my_query_y == True %} <p>My var contains a Y</p> {% endif %} But I don't want to use this last option since it would take more queries to do in view. -
Python. Django. How to avoid of logging file's body during logging incoming payload. multipart/form-data
Env: python==2.7 Django==1.8.4 Required: When request come with multipart/form-data required to replace data of file, but keep all other information. Example: print request.data contains following: --------------------------0a79b890de6a2e8f Content-Disposition: form-data; name="image"; filename="example.jpeg" Content-Type: image/jpeg ����JFIFHH��C and here is 2MB of bytes ����J��(!1AQqa ���@���P���?�z▒��h�x*iٍ8� --------------------------0a79b890de6a2e8f Content-Disposition: form-data; name="field_1" example_1 --------------------------0a79b890de6a2e8f Content-Disposition: form-data; name="field_2" example_2 Expected: --------------------------0a79b890de6a2e8f Content-Disposition: form-data; name="image"; filename="example.jpeg" Content-Type: image/jpeg <file-data> --------------------------0a79b890de6a2e8f Content-Disposition: form-data; name="field_1" example_1 --------------------------0a79b890de6a2e8f Content-Disposition: form-data; name="field_2" example_2 -
Celery Django Deployment fails with Elastic Beanstalk because of ImportError: cannot import name 'Celery' (ElasticBeanstalk::ExternalInvocationError)
I am getting errors after trying to deploy a django app after configuring celery. Its working fine in local environment. It looks like nither celery beats or worker is starting. I am getting error while trying to run the celery worker through superviserd [i-063a3b57f40eb2ffa] [2019-02-27T13:04:39.139Z] INFO [22820] - [Application update app-8bc8-190227_130333@187/AppDeployStage0/EbExtensionPostBuild/Infra-EmbeddedPostBuild/postbuild_0_django_brain_dev/Command 04_start_celery_beat] : Completed activity. Result: celeryd-beat: ERROR (not running) celeryd-beat: ERROR (abnormal termination) [i-063a3b57f40eb2ffa] [2019-02-27T13:04:40.021Z] INFO [22820] - [Application update app-8bc8-190227_130333@187/AppDeployStage0/EbExtensionPostBuild/Infra-EmbeddedPostBuild/postbuild_0_django_brain_dev/Command 05_start_celery_worker] : Starting activity... [i-063a3b57f40eb2ffa] [2019-02-27T13:04:42.397Z] INFO [22820] - [Application update app-8bc8-190227_130333@187/AppDeployStage0/EbExtensionPostBuild/Infra-EmbeddedPostBuild/postbuild_0_django_brain_dev/Command 05_start_celery_worker] : Completed activity. Result: celeryd-worker: ERROR (not running) celeryd-worker: ERROR (abnormal termination) from celery import Celery File "/opt/python/current/app/django_app/celery.py", line 3, in <module> from celery import Celery ImportError: cannot import name 'Celery' (ElasticBeanstalk::ExternalInvocationError) Container Commands : 02_celery_tasks_config: command: "cat .ebextensions/files/celery_configuration.txt > /opt/elasticbeanstalk/hooks/appdeploy/post/run_supervised_celeryd.sh && chmod 744 /opt/elasticbeanstalk/hooks/appdeploy/post/run_supervised_celeryd.sh" leader_only: true 03_celery_tasks_run: command: "sed -i 's/\r$//' /opt/elasticbeanstalk/hooks/appdeploy/post/run_supervised_celeryd.sh" leader_only: true 04_start_celery_beat: command: "/usr/local/bin/supervisorctl -c /opt/python/etc/supervisord.conf restart celeryd-beat" leader_only: true 05_start_celery_worker: command: "/usr/local/bin/supervisorctl -c /opt/python/etc/supervisord.conf restart celeryd-worker" celery configuration.txt contains #!/usr/bin/env bash # Get django environment variables celeryenv=`cat /opt/python/current/env | tr '\n' ',' | sed 's/export //g' | sed 's/$PATH/%(ENV_PATH)s/g' | sed 's/$PYTHONPATH//g' | sed 's/$LD_LIBRARY_PATH//g' | sed 's/%/%%/g'` celeryenv=${celeryenv%?} # Create celery configuraiton script celeryworkerconf="[program:celeryd-worker] ; Set full path to … -
how to register users of different kinds using different tables in django?
I'm new to django, I want to register users using different tables for different users like students, teaching staff, non teaching staff, 3 tables. How can i do it instead of using default auth_users table for registration -
Django Rest Framework Test: How to refresh a relation?
I have a permission in Django Rest Framework: from annoying.functions import get_object_or_None from django.utils.translation import ugettext_lazy as _ from rest_framework import permissions from restaurants.models import Restaurant class TableBelongsToRestaurantPermission(permissions.BasePermission): """ Permission to check if the table belongs to the restaurant in the request. This ensures (together with the UserOwnsRestaurantPermission) that owner can change the QR code of a restaurant that he doesn't own. """ message = TABLE_BELONGS_TO_RESTAURANT_PERMISSION_DENIED_MESSAGE def has_object_permission(self, request, view, obj): if not obj.table: return True slug = request.data.get("restaurant_slug", "") restaurant = get_object_or_None(Restaurant, slug=slug) if restaurant: return restaurant.table_set.filter(id=obj.table.id).exists() return False And now, I wrote tests for this: from unittest import mock from allauth.account.models import EmailAddress from django.contrib.auth import get_user_model from django.test import TestCase from addresses.models import (Address, City, Country, PostalCode, State, StreetName) from core.utils import QR_CODE_FUNCTIONS from employments.models import Employment from licenses.models import RestaurantLicense from profiles.models import UserOwnerProfile from qrcodeproperties.models import QRCodePropertyCheckinUser from restaurants.models import Restaurant from tables.models import Table from ...models import QRCode, QRCodeFunction from ..permissions import TableBelongsToRestaurantPermission User = get_user_model() USER_OWNER_EMAIL = "owner@burgergrill.de" USER_OWNER_NAME = "Owner" USER_PASSWORD = "test1234test" ISO_ALPHA_2_CODE = "DE" STATE_NAME = "NRW" CITY_NAME = "Köln" STREET_NAME = "Burgerstraße" POSTAL_CODE = "32062" STREET_NUMBER = "119" RESTAURANT_NAME = "Burgergrill" RESTAURANT_SLUG = "burgergrill" TABLE_NUMBER = 1 OTHER_RESTAURANT_NAME = … -
autologin for default user in django python app
Can someone help me here: I need something that will land user direclty to Homepage with default username and password hardcoded in code, like autologin for one user in app evry time visit on url it will not ask for username and password. Login window So this window will only use if some user other than default one wants to login to system. how can i achieve this. -
Django virtualenvwrapper environment variables in production
I'm setting up a Django project on a server, following this guide on DigitalOcean. However, I'm very unfamiliar with Gunicorn and nginx, so I'm running into issues. The server is running Ubuntu 18.04, Python 3.6.7, Django 2.1.3, virtualenvwrapper 4.8.4, gunicorn 19.9.0. When running curl --unix-socket /run/gunicorn.sock localhost returns curl: (56) Recv failure: Connection reset by peer I'm suspecting it is the way I handle the SECRET_KEY of Django. I'm using virtualenvwrapper to handle my virtual environments and set environment variables in the postactivate and unset them in predeactivate in the following manner: postactivate: if [[ -n $SECRET_KEY ]] then export SECRET_KEY_BACKUP=$SECRET_KEY fi export SECRET_KEY='my-secret-key' predeactivate: if [[ -n $SECRET_KEY_BACKUP ]] then export SECRET_KEY=$SECRET_KEY_BACKUP unset SECRET_KEY_BACKUP else unset SECRET_KEY It's clear that the variables are not available unless the virtual env is activated. How do gunicorn work with virtual environments? Is there a way to have gunicorn activate the environment? Otherwise, what is best practice when it comes to the SECRET_KEY? Thank you very much! -
How to use Cron Job with Django views?
I want to schedule a job which sends the csv files from FTP server to my Django view, Which further manipulates the file and save it in database. I have never used Cron so I need a suggestion on how to execute this in the best possible way. -
Doesn't get past .load jQuery line in 'django-bootstrap-modal-forms' plugin code, Create View form in modal
I'm not familiar with javascript but I've been commenting out this js plugin, made for django projects, and using .modal("show") as a signifier for when the code actually had executed - and I cannot see why this doesn't show the modal (meaning it never got past the load statement). modal_forms.js (function ($) { // Open modal & load the form at formURL to the modalContent element var newForm = function (modalID, modalContent, modalForm, formURL, errorClass, submitBtn) { ##IT WOULD SHOW MODAL IF SCRIPT HERE## $(modalContent).load(formURL, function () { $(modalID).modal("show"); ##DESIGNED TO SHOW HERE BUT DOESNT## $(modalForm).attr("action", formURL); // Add click listener to the submitBtn ajaxSubmit(modalID, modalContent, modalForm, formURL, errorClass, submitBtn); }); }; // Add click listener to the submitBtn var ajaxSubmit = function (modalID, modalContent, modalForm, formURL, errorClass, submitBtn) { ...}; // Check if form.is_valid() var isFormValid = function (modalID, modalContent, modalForm, formURL, errorClass) { ...}; $.fn.modalForm = function (options) { // Default settings var defaults = { modalID: "#modal", modalContent: ".modal-content", modalForm: ".modal-content form", formURL: null, errorClass: ".invalid", submitBtn: ".submit-btn" }; // Extend default settings with provided options var settings = $.extend(defaults, options); return this.each(function () { // Add click listener to the element with attached modalForm $(this).click(function (event) … -
django annotate on select_related field
My simplified models: class Product(models.Model): name = models.CharField() class Price(models.Model): product = models.OneToOneField('Product', primary_key=True) value = models.DecimalField() class Cart(models.Model): product = models.ForeignKey('Product') qnt = models.IntegerField() Why does Cart.objects.select_related('product__price').annotate(sum=F('product__price__value') * F('qnt')) returns nothing? Replacing F('') to F('value') retunrs error Cannot resolve keyword 'value' into field. Choices are: cart_id, id, product, product_id, qnt -
LinkedIn ads API- gets reposnse with permission error
When I try to get the LinkedIn ads data using the API (https://api.linkedin.com/v2/adAnalyticsV2?q=analytics&dateRange.start.month=1&dateRange.start.day=1&dateRange.start.year=2016&timeGranularity=MONTHLY&pivot=CREATIVE&campaigns=urn:li:sponsoredCampaign:112466001&oauth2_access_token=&format=json) gets response with permission error. Response : { "serviceErrorCode": 100, "message": "Not enough permissions to access: GET-analytics /adAnalyticsV2", "status": 403 } Can anyone help me find out why this error occurs? -
Django ModelForm and mock.patch.object breaking breaking unit test isolation?
I have a unit test that patches the default value of a Django DateTimeField to a known value. This test passes fine, until I introduce a test that creates a ModelForm based on the same model, at which point the original test starts to fail: Failure Traceback (most recent call last): File "test_example.py", line 36, in test_init_date_missing self.assertEqual(actual.event_datetime, test_dt) AssertionError: datetime.datetime(2019, 2, 27, 12, 20, 25, 69409) != datetime.datetime(2019, 2, 10, 10, 10, 10) The test passes when run independently of the other, but as soon as I try to run both in the same suite, it fails. It's as if the patching is failing as soon as the form is instantiated in another test. This example code demonstrates the issue: from datetime import datetime from unittest import mock from django import forms from django.test import TestCase from django.db import models from django.utils import timezone class MyExampleModel(models.Model): event_datetime = models.DateTimeField(default=timezone.now) class MyExampleForm(forms.ModelForm): class Meta: model = MyExampleModel fields = ['event_datetime'] class ExampleTest(TestCase): def test_init_date_missing(self): """Tests that date is set automatically when not provided""" # Little bit of magic to mock the default value of a Django Field # Taken from https://stackoverflow.com/questions/18924869/mocking-default-timezone-now-for-unit-tests test_dt = datetime(2019, 2, 10, 10, 10, 10) event_datetime_field … -
When I execute the daphne command, I get an error: No such file or directory
My command is as follows: sudo /home/fanfei/onehomeServer/env/bin/daphne -u /tmp/daphne.sock onehomeServer.asgi:application I got feedback: sudo: unable to execute /home/fanfei/onehomeServer/env/bin/daphne: No such file or directory But this file is in the folder -
how to display result in dropdownlist using django & ajax
i have 3 dependent dropdownlists country city road. where country is pre-populated from the database and based on the selection of the first the second will display the related cities. the problem is that when user select a country the city is populated but the road display undefined yet in the cmd it display the correct answer. models.py from django.db import models class Road(models.Model): name = models.CharField(max_length=50) city = models.ForeignKey("City",on_delete = models.CASCADE, related_name = 'roads') def __str__(self): return str(self.name) class City(models.Model): name = models.CharField(max_length=50) country = models.ForeignKey("Country",on_delete = models.CASCADE, related_name = 'cities') def __str__(self): return str(self.name) class Country(models.Model): name = models.CharField(max_length=50) def __str__(self): return str(self.name) home.html <html> <head> <script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script> <script type="text/javascript" src="http://yourjavascript.com/7174319415/script.js"></script> <script>$(document).ready(function(){ $('select#selectcountries').change(function () { var optionSelected = $(this).find("option:selected"); var valueSelected = optionSelected.val(); var country_name = optionSelected.text(); data = {'cnt' : country_name }; $.ajax({ type:"GET", url:'/getCity', // data:JSON.stringify(data), data:data, success:function(result){ console.log(result); $("#selectcities option").remove(); for (var i = result.length - 1; i >= 0; i--) { $("#selectcities").append('<option>'+ result[i].name +'</option>'); }; }, }); }); $('select#selectcities').change(function () { var optionSelected = $(this).find("option:selected"); var valueSelected = optionSelected.val(); var city_name = optionSelected.text(); data = {'ct' : city_name }; $.ajax({ type:"GET", url:'/getRoads', // data:JSON.stringify(data), data:data, success:function(result){ console.log(result); $("#selectroads option").remove(); for (var i = … -
How do I use django-anysign
This might not be the right platform to "ask" but I am looking for some example code for a simple django-anysign framework. How can I simply add a signature field in my template and save it as part of the form or model? I couldn't find anything online so please help if you can? Thanks -
Django, Nginx, Docker with Postgresql on AWS ElasticBeanstalk - could not translate host name "db" to address: Name or service not known
I am trying to deploy my Django app to AWS ElasticBeanStalk. Everything works fine with Docker compose on my local computer. But when it runs on AWS it gives me this: Image of error docker-compose.yml: version: '3' services: db: image: postgres hostname: db app: build: context: . dockerfile: config/app/Dockerfile command: sh /config/on-container-start.sh hostname: app volumes: - ./app:/app expose: - "8000" depends_on: - db nginx: image: nginx:latest hostname: nginx ports: - "80:8000" volumes: - ./config/nginx:/etc/nginx/conf.d depends_on: - app Nginx # define group app upstream app { # balancing by ip ip_hash; # define server app server app:8000; } # portal server { # all requests proxies to app location / { proxy_pass http://app/; } # only respond to port 8000 listen 8000; # domain localhost server_name localhost; } In settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'postgres', 'USER': 'postgres', 'HOST': 'db', 'PORT': 5432, } } Any help would be greatly appreciated, Thanks -
Apache error: Invalid command 'WSGIPythonHome'
ISSUE: My Apache/httpd server will not launch. journalctl -xe reveals: Feb 27 01:50:12 localhost.localdomain httpd[4398]: AH00526: Syntax error on line 355 of /etc/httpd/conf/httpd.conf: Feb 27 01:50:12 localhost.localdomain httpd[4398]: Invalid command 'WSGIPythonHome', perhaps misspelled or defined by a module not included in the server configuration Feb 27 01:50:12 localhost.localdomain systemd[1]: httpd.service: main process exited, code=exited, status=1/FAILURE Feb 27 01:50:13 localhost.localdomain kill[4399]: kill: cannot find process "" Feb 27 01:50:13 localhost.localdomain systemd[1]: httpd.service: control process exited, code=exited status=1 Feb 27 01:50:13 localhost.localdomain systemd[1]: Failed to start The Apache HTTP Server. SPECS Red Hat Enterprise Linux 7 rh-python36 installed rh-python36-mod_wsgi-4.5.18-1.el7.x86_64 installed virtual env created at /var/www/web-virt-env httpd.conf: WSGIPythonHome /var/www/web-virt-env WSGIPythonPath /var/www/html/somewebsite <VirtualHost *:80> ServerName awebsite.com DocumentRoot /var/www/html/somewebsite WSGIDaemonProcess somewebsite1 python-home=/var/www/web-virt-env WSGIProcessGroup somewebsite1 WSGIScriptAlias / /var/www/html/somewebsite/somewebsite/wsgi.py <Directory /var/www/html/somewebsite/somewebsite> Require all granted </Directory> Alias /static /var/www/html/somewebsite/static <Directory /var/www/html/somewebsite/static> Require all granted </Directory> </VirtualHost> Expected output: I am suspicious that rh-python36-mod_wsgi-4.5.18-1.el7.x86_64 isn't being "found," but I'm not sure how this is working behind the scenes. What can I do to work around this? Or at least, which steps should I take next to trouble shoot this? -
Django - Captcha form not working in any way
I'm triying to add Recaptcha to my login form in Django. I tried different libraries but none of them seems to work, since the captcha form just doesn't appear in my template. Here is my current work:urls.py > path(r'captcha/', include('captcha.urls')), forms.py class NewUserForm(UserCreationForm): email = forms.EmailField(required=True) class YourForm(forms.Form): captcha = CaptchaField() class Meta: model = User fields = ("username", "email", "password1", "password2") def save(self, commit=True): user = super(NewUserForm, self).save(commit=False) user.email = self.cleaned_data['email'] if commit: user.save() return user And here is my login.html template <form action="/your-name/" method="post"> {% csrf_token %} {{ form.captcha }} <input type="submit" value="Submit"> </form> In this case, only the Submit button will appear, but not the captcha form. This is what happened with any other library i tried. Can anyone give me some help? Thanks in advance! -
Django Filter Query by Foreign Key
I'm struggling getting the right query for my project. Here is an example or my model : from django.db import models class Pictures(models.Model): name = models.CharField(max_length=100) bild = models.FileField(upload_to='artikle_pictures/') artikel = models.ForeignKey('artikles', on_delete=models.CASCADE) def __str__(self): return self.name class Artikles(models.Model): name = models.CharField(max_length=100) text = models.TextField(max_length=2000) published = models.BooleanField(default=False) def __str__(self): return self.name how do I get the published artikles from the artikles class including the pictures (if there is one, or more)? Thank you for your help -
how to overwrite variable in template code?
{% with "test" as var %} {% for lab in all_obj %} <option value='{{lab.lab_name}}' onclick="myFunc()" {% var = lab.lab_name %}>{{lab.lab_name}}</option> {% endfor %} This is inside a select tag, How do i change the var to store the option value clicked by user? i tried using {% set %} -----but it showed me a error saying it was expecting a {%endset %} But if i give an end set there,i wouldn't be able to access var in my full html . i'm new to this,and tried a lot of ways,but couldn't overwrite the variable,please help thank you! -
Django sql name of queryset field for RawSql
I need to generate a pretty large GeoJSON dataset. Serializing the queryset to geojson works but is terribly slow. In my case ~30 seconds. Using the PostGIS ST_AsGeoJSON({geometry_field})::json and then creating the datastructure from that queryset takes a couple of seconds, producing the exact same result. So, to use this method around my code, I have a function geojson_queryset(queryset, geom_field, pk_field, other_fields) (quoted in full below). I originally wrote: features_queryset = queryset.extra( select={'geojson_queryset_result': f'ST_AsGeoJSON({geometry_field})::json'})\ .values(*all_fields) But reading the QuerySet API doc for extra(), the method is deprecated and should rather be written as: features_queryset = queryset.annotate( geojson_queryset_result=RawSQL(f'ST_AsGeoJSON({geometry_field})::json', []) ).values(*all_fields) I am not concerned by SQL injection here because these fields are in no way influenced by user input, we just have a geom, a simplified_geom or location. The problem though is when the queryset is performing a join, the name "geom" can become ambiguous. Area.objects.filter(foo=1) is fine but Area.objects.filter(zone__foo=1) will fail if the zone has a geom field too. Using parameters in RawSQL doesn't work because they're intended for values, not column names, so they're quoted. So my question is how can I convert geom to the correct sql column expression like a0.geom ? Full code: sql_injection_geom_regex = re.compile(r'[^a-zA-Z0-9_]') def … -
Add multiple users to model
I am creating a page where only a certain users can access, I would like to add them manualy, at the moment here is what I have models.py class Hotel(models.Model): manager = models.ForeignKey(User, on_delete=models.DO_NOTHING, verbose_name="Manager d'équipe") code = models.CharField(max_length=500,verbose_name="Code hôtel", default="N/A") contact_rh = models.EmailField(max_length=150,verbose_name="Contact RH", default="N/A") contact_gm = models.EmailField(max_length=150,verbose_name="Contact GM", default="N/A") payday = models.CharField(max_length=500,verbose_name="Jour de paye prévu du mois") hotel = models.CharField(max_length=500,verbose_name="Nom de l'hôtel") planning = models.ImageField(default='default.jpg', upload_to='Planning mois en cours') def __str__(self): return self.hotel But of course I cannot add more than one user I cannot figured out. Thanks -
Optimize Django queryset query with Postgres
I'm using Django 2.1 and python 3.6 I have a query that contains other queries and seems to take too long to evaluate when there is a lot of data to process. Basically it reaches the db user timeout (10 seconds) so the query fails, and when I try it without timeout, I get the following error message from DB (postgres)after almost a minute: ERROR: canceling statement due to conflict with recovery DETAIL: User query might have needed to see row versions that must be removed. My question is - how can I make the query more efficient? (all used fields are indexed in DB) This is the query: migration_set__qs = Migration.objects.filter( migration_id=migration_id, migration_version=migration_version, migration_data__generated_id__isnull=False ).values_list( 'object_id', flat=True ) containers__qs = Container.objects.all().exclude( Q(id__in=migration_set__qs) | Q(created_at__gte=turned_on_date) ) limited_containers = containers__qs[0:10] num_containers_processed += limited_containers.count() The 'count()' triggers the evaluation of the query and there it breaks. -
Create Dynamic Through Model
I have many models with ManyToMany fields. class Author(Model): name = CharField() class Publication(Model): name = CharField() authors = ManyToManyField(Author) class Meta: abstract = True class Book(Publication): pass class Article(Publication): pass class Journal(Publication): pass class D(Model): authors = ManyToManyField(Author) class E(Model): authors = ManyToManyField(Author) I want to add ordering field to all ManyToMany fields. What is the best way to automatically do this? Attempt. # Substitution for ManyToMany class AuthorField(ManyToManyField): def __init__(self, **kwargs): class Relationship(Model): entity = models.ForeignKey(???????????) author = models.ForeignKey(Author) ordering = models.PositiveSmallIntegerField(default=1) class Meta: ordering = ('ordering',) kwargs['to'] = Author kwargs['through'] = Relationship super(AuthorField, self).__init__(**kwargs) -
Django ForeignKey related_name='+'
What does '+' value mean, when passed for related_name parameter of models.ForeignKey()? class Foo(models.Model): bar = models.ForeignKey(related_name='+')