Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Elasticbeanstalk Application returns 404 during autoscale
I have a django application running on elastic beanstalk. The application deploys and works fine when I deploy from the command line. However, during an autoscale, healthcheck on the new instance created always return 404 from the access_logs. "GET /health/ HTTP/1.1" 404 221 "-" "ELB-HealthChecker/1.0" Interestingly, the application eventually loads after about 20 minutes. See my wsgi.conf file below. Is there something I am doing wrong? LoadModule wsgi_module modules/mod_wsgi.so WSGIPythonHome /opt/python/run/baselinenv WSGISocketPrefix run/wsgi WSGIRestrictEmbedded On <VirtualHost *:80> Alias /static/ /opt/python/current/app/staticfiles/ <Directory /opt/python/current/app/staticfiles/> Require all granted </Directory> WSGIScriptAlias / /opt/python/current/app/myapp/wsgi.py <Directory /opt/python/current/app/> Require all granted </Directory> Header always set Access-Control-Allow-Methods "POST,GET,OPTIONS,PUT,DELETE, PATCH" Header always set Access-Control-Allow-Headers "x-requested-with, Content-Type, Accept, origin, authorization, accept, client-security-token, Authorization" WSGIDaemonProcess wsgi processes=3 threads=20 display-name=%{GROUP} \ python-path=/opt/python/current/app:/opt/python/run/venv/lib/python2.7/site-packages:/opt/python/run/venv/lib64/python2.7/site-packages user=wsgi group=wsgi \ home=/opt/python/current/app WSGIProcessGroup wsgi RewriteEngine On RewriteCond %{HTTP:X-Forwarded-Proto} !https RewriteRule !/api/v1.0/church/health/ https://%{SERVER_NAME}%{REQUEST_URI} [L,R=301] </VirtualHost> WSGIPassAuthorization On -
Django app deployed to Digitalocean 502 Bad Gateway
I have copyed my django app (that works locally) to a droplet from Digitalocean where I have installed the django 1-click app. I get 502 Bad Gateway and can't manage to understand why. 2018/03/13 22:25:06 [error] 2104#2104: *44 upstream prematurely closed connection while reading response header from upstream, client: 139.162.251.201, server: _, request: "GET / HTTP/1.0", upstream: "http://unix:/home/django/gunicorn.socket:/" 2018/03/13 22:28:19 [error] 2104#2104: *46 recv() failed (104: Connection reset by peer) while reading response header from upstream, client: 93.55.242.118, server: _, request: "GET / HTTP/1.1", upstream: "http://unix:/home/django/gunicorn.socket:/", host: "46.101.7.245" 2018/03/13 22:31:51 [error] 2104#2104: *49 recv() failed (104: Connection reset by peer) while reading response header from upstream, client: 93.55.242.118, server: _, request: "GET / HTTP/1.1", upstream: "http://unix:/home/django/gunicorn.socket:/", host: "46.101.7.245" 2018/03/13 22:32:05 [error] 2104#2104: *52 connect() to unix:/home/django/gunicorn.socket failed (111: Connection refused) while connecting to upstream, client: 93.55.242.118, server: _, request: "GET /admin HTTP/1.1", upstream: "http://unix:/home/django/gunicorn.socket:/admin", host: "46.101.7.245" 2018/03/13 22:40:18 [error] 2104#2104: *55 recv() failed (104: Connection reset by peer) while reading response header from upstream, client: 93.55.242.118, server: _, request: "GET /admin HTTP/1.1", upstream: "http://unix:/home/django/gunicorn.socket:/admin", host: "46.101.7.245" 2018/03/13 22:40:23 [error] 2104#2104: *55 recv() failed (104: Connection reset by peer) while reading response header from upstream, client: 93.55.242.118, server: _, request: "GET … -
Django - call view method when including template
Is it possible in Django to have a view method associated to template, so when I {% include %} a child template in my parent template, the child template can call it's view method and get some data? Or the only way is to have a single view method associated to url that collects data for every template? -
Spaces in url query not getting decoded in django
I have the following URL query - http://localhost:8000/api/passenger-census/?public_location_description==SW%206th%20&%20Salmon however, the spaces are not being decoded and the resulting query that django parses is GET /api/passenger-census/?public_location_description=SW%206th%20&%20Salmon which returns a null since the string to be found is "SW 6th & Salmon". Django code views.py - class PassengerCensusViewSet(viewsets.ModelViewSet): queryset = PassengerCensus.objects.all() serializer_class = PassengerCensusSerializer filter_backends = (SearchFilter,DjangoFilterBackend,OrderingFilter,) search_fields = ('route_number', 'direction','service_key','stop_seq', 'location_id','public_location_description',) filter_fields = ('summary_begin_date','route_number','direction','service_key','stop_seq','location_id', 'public_location_description','ons','offs','x_coord','y_coord','geom_2913','geom_4326',) ordering_fields = '__all__' serializer.py class PassengerCensusSerializer(serializers.ModelSerializer): class Meta: model = PassengerCensus fields = '__all__' What is the issue here? -
Django 2.0 ipn callback => Forbidden (CSRF cookie not set) despite @csrf_exempt
I use Django 2.0 and I want to accept an IPN from a remote third-party on my url http://example.com/ipn/ This is my url: urlpatterns = [ ... # url for ipn url(r'^ipn/$', views.index, name='ipn'), ... ] This is my view: # decorator from django.views.decorators.csrf import csrf_exempt @csrf_exempt def ipn(request): ''' process ipn call from merchant''' ipn = get_data_from_ipn(request) in my settings.py: ALLOWED_HOSTS = ['ipnsender.net'] ... I'd like that only the ipn view does not use csrf, but I can not understand why I do have the following error although the documentation only tells you need @csrf_exempt decorator. My log tells me every time: Forbidden (CSRF cookie not set.): /ipn/ [13/Mar/2018 22:36:50] "POST /ipn/ HTTP/1.1" 403 2868 -
Django Admin looks ugly - Impossible to load any static files
I'm working on a Django REST project and I used to send my code on Git server. Every css and static files was working fine. Now that I've fetch the project on a new pc, it's now impossible to load any css or js files either on the admin page or the home page. Whenever I load the Django admin page, I get this kind of error in the console: GET http://localhost:8080/static/admin/css/base.css net::ERR_ABORTED And the css doesn't load I also got a similar error when I load the home page: GET http://localhost:8080/static/css/main.css net::ERR_ABORTED I run my project on ubuntu 16.0.4 in a virtualenv (using vagrant) and I use Django 3.5. Here is my directory tree And here is a sample of my settings/base.py file : STATIC_URL = '/static/' STATICFILES_DIRS =[ os.path.join('./', 'static'),] MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join('./', 'media') The images on media folder load very well. I don't know what's wrong, I've tried many workarounds on Google and many other SO related issues and nothing work. I'm lost, please help ! -
Django multiple image upload is possible?
Firstly sory for my bad english. I use python Django framework and ı am use StackedInline when uploading photos. I need to upload the images collectively, not individually. Is this possible? -
media files aren't served to template in django
I trying to serve media files to the template but make them inaccessible from url, and the opposite is happening when i do: http://localhost:8000/media/210000002A.tif I get prompted to download the files so it is being served when accessing from the address bar but in the template I have: <img src="{{ MEDIA_URL }}210000002A.tif"/> and it is not working my dir contains -project -app -media -static -template and i have this is my urls.py if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) and this in my settings.py MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR,'media') -
Adding cloumns to an existing django table witha . postgreSQL db
Ive been searching around for how to do this an di think i broke my table I tried adding dealership = models.ForeignKey('Employee', null=True) To the field to the models.py, since i noticed thats where my other column fields were, and now the entire table is gone. After some more research i saw that its supposed to be added to the migrations location and then run $ python models.py migrations My question is how do i properly add the column, the db already has the information for the column data i cant imagine its that difficult to simply pull that info and how do i get my table back? The table seems to have vanished after i added to the models.py manually and when i tried undoing it just never came back. -
Save object data in list and use in parameter
I need to use the object details of obj to save in a list or some sort to use as a parameter in my send_order_verification() function. def order(request): if request.method == 'POST': form = OrderForm(request.POST) if form.is_valid(): obj = form obj.save() send_order_verification(order_details, obj.email) This is my send_order_verification() function: def send_order_verification(order_details, email): return send_mail( ('Thank you for your order #{0}', x), ('Name: {0}\nEmail: {1}\nTelephone: {2}', x, y, z), [settings.EMAIL_SEND_TO], ['{0}' % email] ) How could this be done? I tried with order_details = [obj.name, obj.email, obj.telephone] but can't access it with order_details[0] and so forth. -
Django app only works on Debug=True Heroku
I thought I had this solved but I guess not. I've got my Django app on Heroku, and it works perfectly with DEBUG = True but does not work with DEBUG = False. This tells me that I have a problem with my static files, as Django doesn't support static files during DEBUG = False. For that, I'm using Whitenoise. Would someone mind reviewing my settings files to see where I've gone wrong. First my file structure: POTRTMS | +---config | | | urls.py | views.py | wsgi.py | +---settings | | | | | base.py | | local.py | | production.py base.py import os from django.utils import timezone import dj_database_url from decouple import config from .aws.conf import * import django_heroku GOOGLE_MAPS_API_KEY = config('GOOGLE_MAPS_API_KEY') EASY_MAPS_GOOGLE_MAPS_API_KEY = config('GOOGLE_MAPS_API_KEY') BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TEMPLATE_DIR = os.path.join(BASE_DIR, 'templates') STATIC_ROOT = os.path.join(PROJECT_ROOT, 'staticfiles') STATIC_URL = '/static/' # Extra places for collectstatic to find static files. STATICFILES_DIRS = [ os.path.join(PROJECT_ROOT, 'static'), ] print(STATICFILES_DIRS) # Simplified static file serving. # https://warehouse.python.org/project/whitenoise/ STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' # Application definition INSTALLED_APPS = [ 'dal', 'dal_select2', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.sites', # Disable Django's own staticfiles handling in favour of WhiteNoise, for # greater consistency between gunicorn … -
using foreign key set in django models django rest framework
I am having an interesting problem. I am using the foriegn key call in the relations mananger. I.e. if I want all the objects from a related model known as hamsters the call would be hamsters_set now here is a working model attached to a serializer everything is working in this implementation. class SearchCity(models.Model): city = models.CharField(max_length=200) class SearchNeighborhood(models.Model): city = models.ForeignKey(SearchCity, on_delete=models.CASCADE) neighborhood = models.CharField(max_length=200) class CityNeighborhoodReadOnlySerializer(serializers.ModelSerializer): searchneighborhood_set = SearchNeighborhoodSerializer(many=True, read_only=True) class Meta: model = SearchCity fields = ('pk','city','searchneighborhood_set') read_only_fields =('pk','city', 'searchneighborhood_set') but with this new model in which I am trying to do the same thing, I am getting an attribute error class Room(models.Model): venue = models.ForeignKey(Venue, on_delete=models.CASCADE) name = models.CharField(max_length=100, null=True, blank=True) online = models.BooleanField(default=False) description = models.CharField(max_length=1000, blank=True, null=True) privateroom = models.BooleanField(default=False) semiprivateroom = models.BooleanField(default=False) seatedcapacity = models.CharField(max_length=10, null=True, blank=True) standingcapacity = models.CharField(max_length=10, null=True, blank=True) minimumspend = models.PositiveSmallIntegerField(blank=True, null=True) surroundsoundamenity = models.BooleanField(default=False) outdoorseatingamenity = models.BooleanField(default=False) stageamenity = models.BooleanField(default=False) televisionamenity = models.BooleanField(default=False) screenprojectoramenity = models.BooleanField(default=False) naturallightamenity = models.BooleanField(default=False) wifiamenity = models.BooleanField(default=False) wheelchairaccessibleamenity = models.BooleanField(default=False) cocktailseatingseatingoption = models.BooleanField(default=False) classroomseatingoption = models.BooleanField(default=False) ushapeseatingoption = models.BooleanField(default=False) sixtyroundseatingoption = models.BooleanField(default=False) boardroomseatingoption = models.BooleanField(default=False) theaterseatingoption = models.BooleanField(default=False) hallowsquareseatingoption = models.BooleanField(default=False) class RoomImage(models.Model): room = models.ForeignKey(Room, on_delete=models.CASCADE) order = models.PositiveSmallIntegerField(blank=True, null=True) imageurl = … -
All urls not showing up on django.rest_framework documentation
This is my main urls.py urlpatterns = [ url(r'^', include_docs_urls(title='Foot The Ball API')), url(r'^admin/', admin.site.urls), url(r'^api/v1/aggregator/', include('aggregator.urls')), url(r'^api/v1/bouncer/', include('bouncer.urls')), ] These are the urls in bouncer.urls urlpatterns = [ url(r'^login/$', LoginView.as_view(), name='login'), url(r'^logout/$', LogoutView.as_view(), name='logout'), url(r'^register/(?P<location_id>[\w.-]+)/$', RegisterView.as_view(), name='register'), url(r'^location/$', LocationView.as_view(), name='location'), ] I'm using rest_framework.documentation. Strangely only login and logout view show up in the documentation home page. Can someone help as to what's going on here? -
Nginx, Django, and Gunicorn still receiving nginx default page
I am having trouble setting up my webserver to serve up my Django web application. I read this tutorial to help me get started, but alas my server only shows the default nginx "welcome page". My gunicorn_start file looks like this: source /home/ubuntu/blog/my_blog/bin/activate export DJANGO_SETTINGS_MODULE=$DJANGO_SETTINGS_MODULE export PYTHONPATH=$DJANGODIR:$PYTHONPATH RUNDIR=$(dirname $SOCKFILE) test -d $RUNDIR || mkdir -p $RUNDIR exec /home/ubuntu/blog/my_blog/bin/gunicorn ${DJANGO_WSGI_MODULE}:application \ --name $NAME \ --workers $NUM_WORKERS \ --user=$USER --group=$GROUP \ --bind=$SOCKFILE \ --log-level=debug \ --log-file=- My nginx sites-avaliable file looks like this: upstream my_site_server{ server unix:/home/ubuntu/blog/Website/my_site/my_site.sock; } server { listen 80; server_name 13.229.113.194; access_log /home/ubuntu/logs/nginx-access.log; error_log /home/ubuntu/logs/nginx-error.log; location = /favicon.ico { access_log off; log_not_found off; } location /static { root /home/ubuntu/blog/Website/my_site/static/; } location / { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_redirect off; if (!-f $request_filename) { proxy_pass http://my_site_server; break; } } } GUnicorn does create the my_site.sock file, but nginx seems to be denied when trying to read it. The error being: 2018/03/13 19:50:11 [error] 17713#0: *1 connect() to unix:/home/ubuntu/blog/Website/my_site/my_site.sock failed (111: Connection refused) while connecting to upstream, client: 74.43.49.203, server: goggleheadedhacker.com, request: "GET / HTTP/1.1", upstream: "http://unix:/home/ubuntu/blog/Website/my_site/my_site.sock:/", host: "goggleheadedhacker.com" 2018/03/13 19:50:24 [error] 17713#0: *3 connect() to unix:/home/ubuntu/blog/Website/my_site/my_site.sock failed (111: Connection refused) while connecting to upstream, client: 74.43.51.94, server: goggleheadedhacker.com, … -
Django dynamic/runtime migrations: what's up?
I am aware that it is widly deprecated or documented in way too old posts, but I think I've got good reasons to be willing to update some of my Django models dynamically, and repercut corresponding changes into my PostgreSQL database. TL;DR What's the latest/neatest/most-django2.0-consistency-compliant way to do this? Is it at least possible or documented in any fashion? This approach only allows model creation, not deletions. I have read about django-mutant, is this module out-of-date? Can we dynamically create and resolve individual migrations? In the end, this would mean nothing but using django as a plain (yet nice and powerful) wrapper around psql, right? If I trust this post, people will first try to stop me. For this reason, I'll develop my motivation here: My core models (1) are a set of django-canonical, consistent, append only, archive tables, whose structure is simple, fixed forever and explicitly described as regular django models. No fancy stuff here. Do not panic. These non-fancy, consistent archives (1) actually describe the evolution of.. a database (2). (Thus my need for meta-* stuff.) The latter database (2) is more volatile, its shape and content will change over time. However, every change to it (2) is … -
How do I set up an AngularJS-driven form to work with Django password reset functionality?
I'm working on a web page with AngularJS v1.5.6. This page has other forms. I want to add a "Reset password" form to this page. Ideally, the form might look something like this: <div ng-app="app" ng-controller="Ctrl"> <form method="post" name="resetPWForm" ng-submit="resetPW(resetPW.email)"> <small>{{ resetPW.msg }}</small> <input placeholder="Email" type="email ng-model="resetPW.email"> </form> </div> I'd like resetPW() to go something like this: $scope.resetPW = function(email){ $http.post( {"email":email}, "path/for/resetting/email") }.then(function(response){ if(response.success==false){ $scope.resetPW.msg = "There was a problem. Please try again."; return; } alert("Success! Check your email for a link to finish resetting your password."); }); I've seen this Django password reset for tutorial: https://simpleisbetterthancomplex.com/tutorial/2016/09/19/how-to-create-password-reset-view.html. But I'm unsure how I'd apply it to my situation. My questions is how would I set up urls.py and views.py to handle this? -
Handling duplicates in django models
This is my location object class Location(models.Model): country = models.CharField(max_length=255) city = models.CharField(max_length=255, unique=True) latitude = models.CharField(max_length=255) longitude = models.CharField(max_length=255) class Meta: unique_together = ('country', 'city') This is the view in which I create a location, class LocationView(views.APIView): def post(self, request): serializer = LocationSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) else: Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) Now while saving the new location if the database throws duplication error, then I want to not write the new value but fetch the already existent data and return it as a success response message. In sense I want to add another else clause. I'm not sure how to do this in django. Any help appreciated. -
How to save multiple files under in 1 django model
I'm fairly new to Django. I have a model copy, the model copy will contain a student test copy and a mark, usually, i would use a FileField and save the copy to the object, but my problem is that a copy could contain many files (page 1, 2, 3 etc) I was thinking about using a CharField instead that contains the path to a folder that contains the files for that copy, but I don't have a very good idea on how to do that and if you have a better way I would for you to share. here is my model class VersionCopie(models.Model): id_version = models.CharField(db_column='id_Version', primary_key=True, max_length=100) numero_version = models.IntegerField(db_column='numero_Version', blank=True, null=True) note_copie = models.FloatField(db_column='note_Copie', blank=True, null=True) emplacement_copie = models.CharField(db_column='emplacement_Copie', max_length=10000, blank=True, null=True) id_copie = models.ForeignKey('Copie', models.CASCADE, db_column='id_Copie', blank=True, null=True) i just need to know what kind of path i would save to "emplacement_copie" -
pip install mod_wsgi failed. Window server 12, python 3.6.4 64 bit vc++14
I am trying to deploy my django app to a win server12 64bit. The latest apache is installed on the server( from apacheloung distro). build tool is vc15 build tool. Python 3.6.4 64bit. I follow the instruction of https://github.com/GrahamDumpleton/mod_wsgi/blob/develop/win32/README.rst But I kept getting the error message like .... src/server\mod_wsgi.c(4417): error C2065: 'wsgi_daemon_process': undeclared identifier src/server\mod_wsgi.c(4417): error C2223: left of '->group' must point to struct/union src/server\mod_wsgi.c(6052): warning C4244: 'return': conversion from '__int64' to 'long', possible loss of data error: command 'C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\BIN\x86_amd64\cl.exe' failed with exit status 2 ---------------------------------------- Command ""d:\program files\python36\python.exe" -u -c "import setuptools, tokenize;file='C:\Users\ccsadmin\AppData\Local\Temp\pip-build-3ktbwpy9\mod-wsgi\setup.py';f=getattr(tokenize, 'open', open)(file);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, file, 'exec'))" install --recor d C:\Users\ccsadmin\AppData\Local\Temp\pip-aw2siwjx-record\install-record.txt -- single-version-externally-managed --compile" failed with error code 1 in C:\Users\ccsadmin\AppData\Local\Temp\pip-build-3ktbwpy9\mod-wsgi\ I have researched online and couldn't find anything similar to my situation. I have compiled successfully on my dev machine(win 10, python 3.64 32 bit) Please advise. -
Why do I get 'this field is required' error in Django models, is there error in my code?
So I am trying to make User form where A user can Upload picture using File-field in models. I am choosing a picture still it says this field is required (after submiting the form) and unloads the pic. models.py: class Incubators(models.Model): # These are our database files for the Incubator Portal incubator_name = models.CharField(max_length=30) owner = models.CharField(max_length=30) city_location = models.CharField(max_length=30) description = models.TextField(max_length=100) logo = models.FileField() verify = models.BooleanField(default = False) def get_absolute_url(self): return reverse('main:details', kwargs={'pk': self.pk}) incubator-form.html <form method="post" novalidate> {% csrf_token %} {{ form.as_p }} <button type="submit">Submit</button> </form> I have added the following code in site's main urls.py: if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) And added the following to settings.py MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' I have even created media folder in the project directory. I have another class with same FileField which works fine. The problem is only in this class. -
502 Bad Gateway Django/nginx/gunicorn
I have deployed my app but when I try to access the url the browser responses me: 502 Bad Gateway Nginx log: 2018/03/13 19:46:10 [error] 15183#15183: *178 connect() failed (111: Connection refused) while connecting to upstream, client: My IP, server: example.com, request: "GET /favicon.ico HTTP/2.0", upstream: "http://127.0.0.1:8000/favicon.ico", host: "example.com", referrer: "https://example.com/" gunicorn service: [Unit] Description=gunicorn daemon After=network.target [Service] User=root Group=www-data WorkingDirectory=/opt/viomapp_project/viomapp ExecStart=/opt/viomapp_project/bin/gunicorn --access-logfile - --workers 5 - -bind unix:/opt/viomapp_project/viomapp/viomapp.sock viomapp.wsgi:application [Install] WantedBy=multi-user.target gunicorn status active (running) and without errors. nginx status without errors. nginx/sites-available: server { # SSL configuration listen 443 ssl http2 default_server; listen [::]:443 ssl http2 default_server; ssl_certificate /etc/letsencrypt/live/viomapp.com/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/viomapp.com/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot root /usr/share/nginx/www; index index.html index.htm; # Make site accessible from http://localhost/ server_name viomapp.com www.viomapp.com; location /static/ { alias /opt/viomapp_project/viomapp/static/; expires 30d; } location / { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_redirect off; proxy_pass http://127.0.0.1:8000; proxy_pass_header Server; proxy_set_header X-Real-IP $remote_addr; # proxy_set_header X-Scheme $scheme; proxy_connect_timeout 10; proxy_read_timeout 10; # proxy_set_header SCRIPT_NAME /; } } server { if ($host = www.viomapp.com) { return 301 https://$host$request_uri; } # managed by Certbot if ($host = viomapp.com) { return 301 https://$host$request_uri; … -
How to reinstall requirements.txt
I'm working in this shared Django project, a colleague is the owner of the repo in Github. The problem I am facing right now is that he added raven to his packages and in github the requirements.txt file is updated, however when I tried with git pull, locally, my requirements.txt does not have raven added. He told me that I have to reinstall requirements.txt so I tried with pip freeze > requirements.txt but nothing change. How can I update my requirements.txt file according the updates made from Github? -
django rawsql postgres nested json/jsonb query
I have a jsonb structure on postgres named data where each row (there are around 3 million of them) looks like so: [{"number": 100, "key": "this-is-your-key", "listr": "20 Purple block, THE-CITY, Columbia", "realcode": "LA40", "ainfo": {"city": "THE-CITY", "county": "Columbia", "street": "20 Purple block", "var_1": ""}, "booleanval": true, "min_address": "20 Purple block, THE-CITY, Columbia LA40"}, .....] I would like to query the min_address field the fastest possible way. In Django I tried to use: APModel.objects.filter(data__0__min_address__icontains=search_term) but this takes ages to complete (also, "THE-CITY" is in uppercase, so, I am having to use icontains here. I tried dropping to rawsql like so: cursor.execute("""\ SELECT * FROM "apmodel_ap_model" WHERE ("apmodel_ap_model"."data" #>> array['0', 'min_address']) @> %s \ """,\ [json.dumps([{'min_address': search_term}])]) but this throws me strange errors like: LINE 4: @> '[{"min_address": "some lane"}]' ^ HINT: No operator matches the given name and argument type(s). You might need to add explicit type casts. I am wondering what is the fastest way I can query the field min_address by using rawsql cursors. -
Python 3 Timedelta OverflowError
I have a large database that I am loading into an in-memory cache. I have a process that does this iterating through the data day by day. Recently this process has started throwing the following error: OverflowError: date value out of range for the line start_day = start_day - datetime.timedelta(days = 1) This is running in Python 3.4.3 on Ubuntu 14.04.5 Thanks! -
Python Migrate issue while setting up Django site
I am trying to learn Django however when I run python manage.py runserver I get Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/home/devopsguy/djangogirls/myvenv/lib/python3.6/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/home/devopsguy/djangogirls/myvenv/lib/python3.6/site-packages/django/core/management/__init__.py", line 308, in execute settings.INSTALLED_APPS File "/home/devopsguy/djangogirls/myvenv/lib/python3.6/site-packages/django/conf/__init__.py", line 56, in __getattr__ self._setup(name) File "/home/devopsguy/djangogirls/myvenv/lib/python3.6/site-packages/django/conf/__init__.py", line 41, in _setup self._wrapped = Settings(settings_module) File "/home/devopsguy/djangogirls/myvenv/lib/python3.6/site-packages/django/conf/__init__.py", line 110, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 674, in exec_module File "<frozen importlib._bootstrap_external>", line 781, in get_code File "<frozen importlib._bootstrap_external>", line 741, in source_to_code File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/home/devopsguy/djangogirls/mysite/settings.py", line 108 TIME_ZONE = "Asia/Calcutta' ^ SyntaxError: EOL while scanning string literal I am new to Django and python so am clueless about what I broke. Any help would be greatly appreciated.