Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
nexmo implementation in django module 'requests' has no attribute 'post'
While trying to implement the 2fa app from the example in the following link: Nexmo 2fa for Django i'm getting the following error: module 'requests' has no attribute 'post' screenshot -
Django logging fails because of wrong system Locale
I have a Django app, which fails to log with the error UnicodeEncodeError: 'ascii' codec can't encode character. The problem is that the system locale is the CentOS default locale, which is ASCII. The admins don't want to change the system-wide locale on their servers, saying that the apps should be able to run in a clean environment. We circumvented the problem for the Django apps themselves by adding this to the uwsgi.ini: env = LANG=en_US.UTF-8 env = LANGUAGE=en_US.en env = LC_ALL=en_US.UTF-8 However, uwsgi.ini has no effect on the code run as a django management command, and we have a lot of work done in those. What could be the best way to fix that? UPD: We also tried setting the locale in the settings.py file, but that didn't help. -
Django Models Field.E340 : ManytoMany relationship same intermediate table name in 2 different apps
We are trying to makemigrations and migrating the app level model to respective databases using database router. We have one model file in one app pointing to one database and same structured models with table name with some tables added are being created in other app then intermediate table name is creating error. Error : master.LegalTbl.legal_field_name: (field.E340) The field's intermediary table 'tbl_legal_tbl' clashes with the table name of 'user.LegalTbl'. -
Overriding delete() vs using pre delete signal
I have a model where i would like when an object gets deleted, instead of being deleted a status is updated. This was achieved with following code: def delete(self, using=None, keep_parents=False): self.status = Booking.DELETED self.save() The manager was updated so that in the rest of the application i never get presented deleted bookings. class BookingManager(models.Manager): def get_queryset(self): return super().get_queryset().exclude(status=Booking.DELETED) class BookingDeletedManager(models.Manager): def get_queryset(self): return super().get_queryset().filter(status=Booking.DELETED) class Booking(models.Model): PAYED = 0 PENDING = 1 OPEN = 2 CANCELLED = 3 DELETED = 4 objects = BookingManager() deleted_objects = BookingDeletedManager() ... Now i have read up on django signals and was wondering wheter it would be better to use the pre delete signal here. The code could be changed so that in the pre delete receiver a duplicate is created with status 'deleted' and the original booking is just deleted. In the documentation it states that these signals should be used to allow decoupled applications get notified when actions occur elsewhere in the framework. It seems the signal is a good a solution but this nuance in the documentation makes me think it's maybe not what i want and overriding might just be the way to go. This is not really the β¦ -
Bad Request (400) when upload image in admin panel
I am working with django 1.11 and I have problem with uploding image in admin panel. When I am uploding image in admin panel and click save I receive Bad Request (400). I thought that was something with allowed_hosts but I have addresses. -
cannot import name 'CacheControlAdapter' Django 1.11.6
I am using Django 1.11.6 by using VisualStudio 2017 and try to run my project i still get error from pip._internal.compat import WINDOWS File "E:\Panorama\Panorama\env\lib\site-packages\pip_internal__init__.py", line 42, in from pip._internal import cmdoptions File "E:\Panorama\Panorama\env\lib\site-packages\pip_internal\cmdoptions.py", line 16, in from pip._internal.index import ( File "E:\Panorama\Panorama\env\lib\site-packages\pip_internal\index.py", line 24, in from pip._internal.download import HAS_TLS, is_url, path_to_url, url_to_path File "E:\Panorama\Panorama\env\lib\site-packages\pip_internal\download.py", line 16, in from pip._vendor.cachecontrol import CacheControlAdapter ImportError : cannot import name 'CacheControlAdapter' -
djnago channels install error
i am trying to create a one to one real-time messaging system using Django. upon searching i found out about django-channels. so i created a virtual env that has python 3.5 installed with latest Django but when i do pip install channels i get : #include "Python.h" ^ compilation terminated. error: command 'x86_64-linux-gnu-gcc' failed with exit status 1 probably because of missing python headers so i did sudo apt get install python3-dev but it still shows the same error.what should i do? pip version: 18 python version: 3.5 django version: 2.1 -
Django Models Field.E340 : ManytoMany relationship same intermediate table name in two different apps
We are trying to makemigrations and migrating the app level model to respective databases using database router. We have one model file in one app pointing to one database and same structured models with table name with some tables added are being created in other app then intermediate table name is creating error. Error : master.LegalTbl.legal_field_name: (field.E340) The field's intermediary table 'tbl_legal_tbl' clashes with the table name of 'user.LegalTbl'. -
How to redirect with querystring in django urlpatterns?
I'm looking for a way to make a redirect from one url to another with query string parameter. Is it possible to get a redirect from /orders/ to /orders-new/?queryParam=1 How should I change RedirectView in a first line? url(r'^orders/$', RedirectView.as_view(pattern_name='orders-new'), name='orders'), url(r'^orders-new/$', orders_list_new, name='orders-new'), -
django Scheduling using python
I am new to Django I am unable to understand the method for the periodically scheduling a string say text =Hello World and display on browser -
How to see the underlying query which includes count() in it, in django
I have the following code in a Django 2 project print(List.objects.filter(user=self.request.user).query) which prints the SQL query which is constructed but the following print(List.objects.filter(user=self.request.user).count().query) throws error print(List.objects.filter(user=self.request.user).count().query) AttributeError: 'int' object has no attribute 'query' I know why it happens, because count() immediately return the count. How do I see the query which it constructed -
Issue with Elasticsearch : ConnectionError
I'm working on different web application in my new society and I get this issue each time I would like to use Elasticsearch (version 6.3.1) : elasticsearch.exceptions.ConnectionError: ConnectionError(: Failed to establish a new connection: [Errno 111] Connection refused) caused by: NewConnectionError(: Failed to establish a new connection: [Errno 111] Connection refused) For example with Django, I execute these commands : sudo service elasticsearch start then python manage.py indexdocs And I get this issue as below. I tried to make : curl -XGET http://localhost:9200 And I obtain this : curl: (7) Failed to connect to localhost port 9200: Connexion refusΓ©e Do you have any idea about this ? I have to authorized something somewhere ? Thank you -
ValueError: not enough values to unpack (expected 2, got 1) when updating environ
I am using environment key for better settings configuration. Initially, i got the following error django.core.exceptions.ImproperlyConfigured: Set the DATABASE_URL environment variable thus, i searched in google and found the following solution settings/base.py import os with open('.envs/.local/.postgres') as fh: os.environ.update(line.strip().split('=', 1) for line in fh) However, this gives me an error too. I get ValueError: not enough values to unpack (expected 2, got 1) -
Django command giving error
I am new to Django and Python having trouble with a Django command. Before the query, I want to let you know that 1) python is installed in my c drive and the path name is C:\Users\admin67\AppDathea\Local\Programs\Python\Python37 2) The Djangp project is in the D drive and the path name is D://wisdompets 3) My python version is python 3.7.0 In the windows shell I give the command python3 manage.py runserver However this command is not running in my windows shell. I have tried all combinations such as python370, python37, python 3.7..0 but nothing works and I keep getting the message (see the attachment). The error traceback that I get in the Windows shell is as below. The term 'python3' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spe lling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:8 + python3 <<<< manage.py runserver + CategoryInfo : ObjectNotFound: (python3:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException Please help me resolve this error. Thanks & Regards Manish -
Django: ManyToMany Field on a model
I have these models: class Unit(AppModel): name = models.CharField(max_length=255) def __str__(self): return self.name class Item(AppModel): title = models.CharField(max_length=255) units = models.ManyToManyField("Unit", symmetrical=False, related_name="items") def __str__(self): return self.title + self.units class Invoice(AppModel): items = models.ManyToManyField("Item", symmetrical=False, related_name="invoices") def __str__(self): return "invoice_" + self.id As you can see, we have an Item with multiple units and an Invoice with multiple items. But, I want each item in an Invoice to have a single unit only. How to achieve that? i.e, some_item.units should return all its type of units. Whereas, for item in some_invoice.items: return item.units should return a single unit. Note: I was not able to frame the title of this Post. Feel free to so. Thanks. -
Mattermost iframe integration Django app
I have apache 2.4 and mattermost 5.2. Both of them are on the same server. I have configured a virtual host for pointing to mattermost on port 8065. Following is my conf file. <VirtualHost *:80> ServerName subdomain.domain.in #ServerAdmin hostmaster@mydomain.com ProxyPreserveHost On # Set web sockets RewriteEngine On RewriteCond %{REQUEST_URI} /api/v[0-9]+/(users/)?websocket [NC,OR] RewriteCond %{HTTP:UPGRADE} ^WebSocket$ [NC,OR] RewriteCond %{HTTP:CONNECTION} ^Upgrade$ [NC] RewriteRule .* wss://127.0.0.1:8065%{REQUEST_URI} [P,QSA,L] RewriteCond %{DOCUMENT_ROOT}/%{REQUEST_FILENAME} !-f <LocationMatch "^/api/v(?<apiversion>[0-9]+)/(?<apiusers>users/)?websocket"> Require all granted ProxyPass ws://127.0.0.1:8065/api/v%{env:MATCH_APIVERSION}/%{env:MATCH_APIUSERS}websocket ProxyPassReverse ws://127.0.0.1:8065/api/v%{env:MATCH_APIVERSION}/%{env:MATCH_APIUSERS}websocket ProxyPassReverseCookieDomain 127.0.0.1 subdomain.domain.in </LocationMatch> <Location /> Require all granted ProxyPass http://127.0.0.1:8065/ ProxyPassReverse http://127.0.0.1:8065/ ProxyPassReverseCookieDomain 127.0.0.1 subdomain.domain.in </Location> </VirtualHost> I am trying to load iframe in following way from anothersubdomain.domain.in/mattermost in Django application <iframe src="http://subdomain.domain.in"></iframe> I am getting Refused to display 'http://subdomain.domain.in/' in a frame because an ancestor violates the following Content Security Policy directive: "frame-ancestors 'self'" I do not want to change in mattermost code. Is there a way to complete this? -
How to calculate number of days, when two DateFields are given? Django
models.py from django.db import models class Leave(models.Model): ... from_date = models.DateField() to_date = models.DateField() def __str__(self): return self.name The above are the two date fields which are defined in my models.py. views.py from django.shortcuts import render, render_to_response from .forms import LeaveRequestForm from django.shortcuts import from .models import Leave ... def get_days(request): data = Leave.objects.all() for x in data : if x.employee_ID == request.user.username: d1 = x.from_date d2 = x.to_date days = d2 - d1 return render(request,"status.html", days) The above code is my trial on getting the number of days. Here, my model is Leave and my form is LeaveRequestForm. In my HTML file to get the number of days I use {{ from_date|timesince:to_date }}, this works but i want to deduct this number of days from a number. base : I'm working on a leave-management project. If a user asks a leave for 5days and he is eligible for 10days. His balance leaves should be equal to 5. How do I achieve this with the views? -
Calculate lat long Distance ORM query python django
Models.py class Restaurant(models.Model): name=models.CharField(max_length=500) email=models.CharField(max_length=500) web=models.CharField(max_length=500) short_description=models.CharField(max_length=500) description=models.CharField(max_length=500) phone=models.IntegerField(blank=True,null=True,default=0) lat =models.FloatField(blank=True,null=True) lng =models.FloatField(blank=True,null=True) # location = models.PointField(null=False, blank=False, srid=4326, verbose_name="Location") address1 = models.CharField(max_length=100) address2 = models.CharField(max_length=100,blank=True) city = models.CharField(max_length=100) state = models.CharField(max_length=2) postalcode = models.CharField(max_length=20) avg_rating=models.FloatField(blank=True,null=True) restaurant_type=models.ForeignKey(RestaurantType,on_delete=models.CASCADE) price=models.IntegerField(blank=True,null=True,default=0) keywords=models.ManyToManyField(RestaurantKeyword,blank=True) def __str__(self): return self.name Raw Query: SELECT id,name,( 3959 * acos ( cos ( radians(" +lat +")) * cos( radians( lat ) ) * cos( radians( lng ) - radians("+lng+") ) + sin ( radians("+lat+") ) * sin( radians( lat ) ) ) ) AS distance FROM newbackend_restaurant In this code raw query is working fine but I'm looking for ORM query in Django. -
Extend startapp in Django 2 to pre-wire App templates, statics, urls etc
How can I extend manage.py startapp command to pre-create various folders and pre-wire templates, statics, urls etc? For example, if I do manage.py startapp myapp within project myproj, the following will be automatically done: Automatic folder creation for myapp\templates\myapp, myapp\static\myapp\css, myapp\static\myapp\js File myapp\urls.py automatically added, with standard content as Django project creation base.html automatically added in app template folder etc. Those are examples which may grow more, need to know where to start looking into all these. -
Should lru cache be used for a function with DB calls
I had a method in my code with look really long to execute. This function is called around 30 times for different currencies, It fetches some data for those currencies from database (psql) .Now I added lru_cache decorator for that function. It decreased execution time very much but I have a doubt that will this method now return old data (values in database may change). My code structure is something like this. @lru_cache def fetch_from_db(symbol): #data fetched from db return data for symbol in allSymbols: list.append(fetch_from_db(symbol)) return list I want to make sure that this data is correct all time. I actually did some tests. For my test data was always new but If anyone thinks that this might break somewhere, Please Do tell Thanks -
Is there a way to mention the database settings while starting the Django app?
From the docs, it looks like the database needs to be present in the settings.py. Is there a way to pass the database details while running python manage.py runserver given the migrations have been completed? -
gauge.js - Relative URL does not work but absolute URL does
I have been experimenting with gauge.js, and reproduced the working 'Usage' code presented on the link only when using an absolute URL, but not when using a relative URL. I did not find anything similar on Github Issue Tracker Working Code <canvas id="foo"></canvas> <script> var opts = { lines: 12, angle: 0.15, lineWidth: 0.44, pointer: { length: 0.9, strokeWidth: 0.035, color: '#000000' }, limitMax: 'false', percentColors: [[0.0, "#a9d70b" ], [0.50, "#f9c802"], [1.0, "#ff0000"]], // !!!! strokeColor: '#E0E0E0', generateGradient: true }; var target = document.getElementById('foo'); var gauge = new Gauge(target).setOptions(opts); gauge.maxValue = 3000; gauge.animationSpeed = 32; gauge.set(2250); </script> <script src="https://bernii.github.io/gauge.js/dist/gauge.min.js"></script> Issue If I replace the above absolute URL with a relative URL, the gauge disappears. What I did was copy the gauge.min.js code from here, and place the file inside my static folder. (Working tree directory below) <script src="../../static/lineoee/gauge.min.js"></script> The above relative URL should be pointing to a valid directory, however I am getting: (index):224 Uncaught ReferenceError: Gauge is not defined at var gauge = new Gauge(target).setOptions(opts); Working Tree Directory β βββ static β β βββ lineoee β β βββ gauge.min.js β βββ templates β β βββ linedetails β β β βββ index.html β β β βββ index.html.save β β βββ β¦ -
Celery (4.2): how to get task id for current task
AIM For the purposes of an alarm clock, I am attempting to 'get' the specific Alarm created by the User in the SetAlarmForm. From the other answers on the same topic (Q1, Q2, Q3), I am attempting the line: objx = Alarm.objects.get(id=run_alarm.request.id). Perhaps, I am missing something obvious or the version of Celery has been updated? ERROR [ERROR/ForkPoolWorker-2] raised unexpected: DoesNotExist('Alarm matching query does not exist') CODE Models.py class Alarm(models.Model): """ Model representing each Alarm """ id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) Views.py class AlarmCreateView(LoginRequiredMixin, CreateView): """ CreateView for User to create the Alarm object """ model = Alarm form_class = SetAlarmForm template_name = 'weather_alarm/set_alarm.html' login_url = "/login/" def form_valid(self, form): self.create_alarm_object(self.request, form) run_alarm.delay() return HttpResponseRedirect(self.get_success_url()) Tasks.py import time from celery import Celery, shared_task, current_task from datetime import datetime from .models import Alarm @shared_task def run_alarm(): """ Function to organise the steps for the alarm using Celery """ objx = Alarm.objects.get(id=run_alarm.request.id) second_countdown = objx.get_alarm_length() # get the length of the alarm, in seconds time.sleep(second_countdown) # wait for the alarm time conditions_satisfied = objx.check_conditionals() # check if conditionals are satisfied if conditions_satisfied == True: # conditions are satified print("Ring ring!") return True else: # conditions aren't satisfied print("I'm only sleeping!") return True -
OperationalError: cursor "_django_curs_<id>" does not exist
We have an online store web-app which is powered by django, postgresql and heroku. For a specific campaign (you can think a campaign like a product to purchase), we have sold 10k+ copies successfully. Yet some of our users are encountered this error according to our Sentry reports. Common specification of these users is; none of them have address information before the purchase. Generally, users fill out address form right after registering. If they don't, they need to fill the form while purchasing the product and submit them together. This is how the trace looks like: OperationalError: cursor "_django_curs_140398688327424_146" does not exist (66 additional frame(s) were not displayed) ... File "store/apps/store_main/templatetags/store_form_filters.py", line 31, in render_form return render_to_string('widgets/store_form_renderer.html', ctx) File "store/apps/store_main/templatetags/store_form_filters.py", line 20, in render_widget return render_to_string('widgets/store_widget_renderer.html', ctx) File "store/apps/store_main/widgets.py", line 40, in render attrs=attrs) + "<span class='js-select-support select-arrow'></span><div class='js-select-support select-arrow-space'><b></b></div>" OperationalError: cursor "_django_curs_140398688327424_146" does not exist So another weird common thing, there are exception messages between sql queries before the failure. You can see it in the image below: I'm adding it if they are somehow related. What may also be related is, the users who get this error are the users who tries to purchase the campaign right after β¦ -
Django command gives errors
I am new to Django and Python and need some help. Before the query, I want to let you know that 1) python is installed in my c drive and the path name is C:\Users\admin67\AppDathea\Local\Programs\Python\Python37 2) The Djangp project is in the D drive and the path name is D://wisdompets 3) My python version is python 3.7.0 In the windows shell I give the command python3 manage.py runserver However this command is not running in my windows shell. I have tried all combinations such as python370, python37, python 3.7..0 but nothing works and I keep getting the message (see the attachment). The error says 'Can' open file...no such directory, etc. etc. Please help me resolve this error. Thanks & Regards Manish