Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django rest framework http 404 detail": "Not found."
Whenever I try to update an itinerary with primary key using PUT request I get HTTP 404 detail": "Not found." api views.py class updateTempItinerary(generics.UpdateAPIView): queryset = tempItinerary.objects.all() serializer_class = tempItinerarySerializer permission_classes = (permissions.AllowAny,) api urls.py url(r'^updatetempitinerary/$(?P<pk>)(?P<itineraryID>)(?P<destinations>)(?P<hotels>)', views.updateTempItinerary.as_view()), itinerary models.py class tempItinerary(models.Model): itineraryID = models.CharField(max_length=100, unique=True) user = models.CharField(max_length=100) country = models.IntegerField() destinations = models.CharField(max_length=100, default='None') hotels = models.CharField(max_length=100, default='None') travelClass = models.CharField(max_length=100) date = models.DateField() travelers = models.IntegerField(default=1) def __unicode__(self): return '%s %s %s %s %s %s %s %s ' % (self.pk, self.travelers, self.date, self.travelClass, self.hotels, self.destinations, self.country, self.itineraryID, self.user) URL im testing on 127.0.0.1:8000/api/updatetempitinerary/?pk=1&format=json& -
AUTH_USER_MODEL refers to model that has not been installed / Apps aren't loaded yet
So I'm trying to change the User model of a project i started a while back. The app's name is main and i have installed it with "main.apps.MainConfig". I am trying to set USERNAME_FIELD = 'email' My apps.py looks like this: from __future__ import unicode_literals from django.apps import AppConfig from django.contrib.auth.models import User class MainConfig(AppConfig): name = 'main' User.USERNAME_FIELD = 'email' This gives me the error django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. I've tried setting USERNAME_FIELD = 'email' through a user.py file. I set AUTH_USER_MODEL = 'main.user' in settings.py and this is my user.py: from django.contrib.auth.base_user import AbstractBaseUser from django.db import models class User(AbstractBaseUser): email = models.EmailField(_('email address'), unique=True) USERNAME_FIELD = 'email' This yields the following error: django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'main.user' that has not been installed I have no idea whats going on here. Any help is appreciated. Thanks in advance! -
sock failed (2: No such file or directory) Django 1.8, Nginx, Gunicorn
I am confused by 502 error at my django project. As far as I understand nginx fails to pass to gunicorn, but I am not sure. I followed all steps from here very accurately https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-16-04 /etc/systemd/system/gunicorn.service: [Unit] Description=gunicorn daemon After=network.target[Unit] Description=gunicorn daemon After=network.target [Service] User=root Group=www-data WorkingDirectory=/home/root/glboy ExecStart=/home/root/glboy/denv/bin/gunicorn --workers 3 --bind unix:/home/root/glboy/closer.sock closer.wsgi:application [Install] WantedBy=multi-user.target /etc/nginx/sites-available/closer and /etc/nginx/sites-enabled: server { listen 80; server_name 46.101.192.66; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/glboy/static; } location / { include proxy_params; proxy_pass http://unix:/home/root/glboy/closer.sock; } } also found tutorial where /etc/nginx/sites-available/default was also edited, tried as well despite I do not fully understand the purpose : server { listen 80; server_name 46.101.192.66; access_log /var/log/nginx/example.log; location /static/ { root /home/glboy/static; expires 30d; } location / { proxy_pass http://127.0.0.1:8000; proxy_set_header Host $server_name; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } } In nginx error log absence of socket is reported /home/root/glboy/closer.sock failed (2: No such file or directory) I just copied the path how should it be according to instruction, but if it's wrong what path is right or what is wrong otherwise? -
google cloud storage file stuck in time after multiple updates/deletions
I have a cloud storage file frozen in time and will not budge. So far I have: recollected static files (Django) and did an rsync to update deleted the static file in question, recollected static files and did an rsync to update deleted the file in the cloud storage console and re-rsynced deleted the entire bucket and made another bucket with the same name, and rsynced all 85 static files onto it again The first few times I changed the static file, collected them, and rsynced, it worked instantly. Now I have this one line var URL = "http://%/api/recipes/delete/&/".replace("%", API_BASE).replace("&", recipe_id); stuck in time, frozen in this bucket. In Django, my file correctly reads var URL = "/api/recipes/delete/&/".replace("&", recipe_id); The change is checked into git. This bucket has not updated at all, and the file was still being served even after I deleted the file. The file was still being served after I deleted the entire bucket, which seems like a bug I'm out of ideas if even deleting and remaking the entire bucket doesn't change anything. Any help appreciated, thank you -
Saving BytesIO to Django ImageField
I have a web scraper that I want to download an image of the page it's scraping and save it as a "screenshot" ImageField in a Django model. I am using this code: def save_screenshot(source,screenshot): box = (0, 0, 1200, 600) im = Image.open(io.BytesIO(screenshot)) region = im.crop(box) tempfile_io = io.BytesIO() region.save(tempfile_io, 'JPEG', optimize=True, quality=70) source.screenshot.save(source.slug_name+"-screenshot",ContentFile(tempfile_io.getvalue()),save=True) It saves the screenshot to the /media/news_source_screenshots/ directory but doesn't save it to the model. The model field is defined as: screenshot = models.ImageField(upload_to='news_source_screenshots',blank=True,null=True) What am I missing? -
Database returned an invalid value in QuerySet.datetimes()
I got this error when I try to access the PayPal IPNs from the admin site. I use Google Mysql and I can't figure out how to apply solutions from similar questions (Typically I've tried with Google Cloud Shell). ValueError at /admin/ipn/paypalipn/ Database returned an invalid value in QuerySet.datetimes(). Are time zone definitions for your database and pytz installed? -
VS Code virtualenv windows path
I was wondering how to set the python path (workspace setting) in vs code in windows when you are working inside a virtualenv? Example: virtualenv folder is on desktop. -
SMTPServerDisconnected Connection unexpectedly closed using sendgrid
I followed this tutorial to set up email sending using Sendgrid. (I tried before using gmail and that also didn't work.) https://sendgrid.com/docs/Integrate/Frameworks/django.html But I am getting SMTPServerDisconnected Connection unexpectedly closed I added this to my settings.py EMAIL_HOST = 'smtp.sendgrid.net' EMAIL_HOST_USER = 'myemail' EMAIL_HOST_PASSWORD = 'mypassword' EMAIL_PORT = 587 EMAIL_USE_TLS = True In my views.py I have this: def email(request): if request.method == 'GET': form = ContactForm() else: form = ContactForm(request.POST) if form.is_valid(): from_email ="myemail" recipients =[] recipients.append(email) subject = 'Hello' message = 'Test message' try: send_mail(subject, message, from_email, recipients, fail_silently=False) except BadHeaderError: return HttpResponse('Invalid Header found.') return redirect('thanks') return render(request, "email.html", {'form': form}) -
Django Meta ordering in related query
How do you set a default order for Django queries that works on related managers? You can set a default order with Meta.ordering: class Subject(Model): title = TextField() class Course(Model): subject = ForeignKey(Subject) class Meta: ordering = ['id'] This will set the order when you run Course.objects.all(). But when you run subject.course_set.all(), the courses can be out of order. -
conver string array to array in javascript
I get the following item back from my django-rest-framework api call: services = "['service1', 'service2', 'service3']" I want services = ['service1', 'service2', 'service3'] In my JavaScript I tried to following services = JSON.parse(services) didn't do anything, also tried $.parseJSON(services) In my serializers I have tried the setting services as ListField, also tried JSONSerializerField() class JSONSerializerField(serializers.Field): # Adapted from http://stackoverflow.com/a/28200902 def to_internal_value(self, data): return json.loads(data) def to_representation(self, value): return value -
Which Python module to use for interpreting HTML form values without editing form page?
I have an HTML form that consists of a ton of different values and form fields, and I want to submit those values to a Python file, and have the Python file return (to the user) whether the value was "correct" or "incorrect". I'm a fairly new programmer, and my only Python web development experience is with Django. I know for Django you have to add a lot to the form to make it usable with Django. Is there a similar framework (not sure if that includes thing like the CGI module) that doesn't require the form to be modified to properly interpret/return script values? Potentially important info: All data is from radio buttons There are an average of 20 sets of 5 radio buttons per form, and 40 total forms. One radio button (per set) has a "correct" value, the other four have an "incorrect" value A user can select one of the five radio buttons per set I do not need to record the values, just give the user a response based on their submission once they have submitted it. Thanks for any help. -
Error while passing the variables to jinja template
This is my code in models symbols = [x.encode('UTF8') for x in Stocks.objects.values_list('symbol', flat = True)] companies = [x.encode('UTF8') for x in Stocks.objects.values_list('company', flat = True)] context = { "symbol": symbols, "company": companies } I am trying to pass the context to a template and the template code (inside the block content). {% for i,j in symbol,company %} {{i}} {{j}} <br> {% endfor %} i tried {{i,j}} as well but it did not work. it is throwing me Could not parse the remainder: ','company'' from ''symbol','company'' -
Django web frame real time data
i am writing a Django project that display data from mysql database, database is constantly getting update, how can i constantly send data in view.py. i tried looking at many modules i came across celery,Tornado, Django channels but they are mostly written for chat applications, also i tried considering using Node.js with Django. but what is the real solution for a simple data update in Django ? Right now I simply use this code in my html file that refresh the page and gets the last data but the problem is that it makes the website run very slow : <script> var myVar = setInterval(ReLoad , 2000); //refresh every 2 seconds function ReLoad() { $("#live").load(document.URL + " #live"); } </script> -
Updating or keeping migrations when sync local project with VPS
I'v got django project on local machine and on VPS. The question is when I update the files shall I replace migrations on VPS with those I had on my local machine or update files but leave VPS migrations as they were? -
Django - How to use my custom filters inside any included template?
I can't make use of my filters on my included child view, the filter works when is written directly, but I need the child view as inclusion... Here is the filter: from django import template from django.template.defaultfilters import stringfilter register = template.Library() @register.filter def lower(value): return value.lower() Here is how I call my template: {% load app_filters %} {% include 'view.template.html' %} view.template.html <h1>{{ 'Hello World!' | lower }}</h1> But the thing is that it doesn't work been included, unless I had to add the {% load app_filters %} inside view.template.html but I need this template for my angular app too, so I can't write this line in the template. How could I inject my custom filters to the included view without modifying the view? It is possible to pass as {% include 'view.template.html' with app_filters=app_filters %}? It is only the idea. -
Django command throws TypeError: handle() got an unexpected keyword argument
I'm using Django 1.10.4 and Python 3.52. When I try to run a Django command via python manage.py my_command I get the following error: Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "path_to_envs/envs/env_name/lib/python3.5/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line utility.execute() File "path_to_envs/envs/env_name/lib/python3.5/site-packages/django/core/management/__init__.py", line 359, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "path_to_envs/envs/env_name/lib/python3.5/site-packages/django/core/management/base.py", line 294, in run_from_argv self.execute(*args, **cmd_options) File "path_to_envs/envs/env_name/lib/python3.5/site-packages/django/core/management/base.py", line 345, in execute output = self.handle(*args, **options) TypeError: handle() got an unexpected keyword argument 'verbosity' I can run a local django server and interact with the admin pages. The app that contains that command is in my settings.py file. At the time of error, the options dictionary contains {'verbosity': 1, 'no_color': False, 'settings': None, 'pythonpath': None, 'traceback': False}. Depending on the random ordering of the dictionary no_color, traceback, and the others will throw the same TypeError. After a day of googling I still can't figure out what the issue is. Has anyone seen this before? -
Signing in through AJAX post request on Django All-auth
According to the documentation of django all-auth , it supports logging in through AJAX requests.When I make a normal post request to "accounts/login/" ,content type of the response header is "text/html". But when I make a ajax call it is "application/json". I am unable to figure what I am doing wrong, I have tried changing the contentType and dataType in ajax call but it gives a 400 Bad request error. I have not modified any URL or view of the default Django all-auth app. I am including the JavaScript code here - <script type="text/javascript"> var $button = $('#login_button'); $button.on('click',function(){ var data = {"csrfmiddlewaretoken" : document.getElementsByName('csrfmiddlewaretoken')[0].value, "login": $('#id_login').val(), "password": $('#id_password').val(), "remember": $('#id_remember').val() }; var temp = {'X-CSRFToken': document.getElementsByName('csrfmiddlewaretoken'[0].value }; $.post({ url : "{% url 'account_login' %}", headers: temp, type: "POST", data : data, contentType: "application/x-www-form-urlencoded", dataType: "text", success : function(data) { // console.log(data); }, }); }); </script> -
Unpacking two huge lists in python
I have two huge lists in python. lets say countries = ['country names'.....] country_codes = ['ccd' .....] I am trying to use for loop to unpack the data and load it into database, but I am getting an error "ValueError: too many values to unpack" need help ... -
Django manage.py search inside ancient paths
I'm using Django 1.8 and I'm under OS X. I moved my project a long time ago from folder a to folder b and everything was fine. No I migrated to a new Mac and installed all my tools, projects, and so on. Now I run into the problem that I can't start my project any more. The command python manage.py shell always tries to find models my old folder a. I also greped my hole project and looked up for some hardwired path but there are none. I'm stuck now. I already search the internet and on stackoverflow but couldn't find any solution for me problem. Thanks in advance. aronadaal >src aronadaal$ python2.7 manage.py makemigrations Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/Library/Python/2.7/site-packages/django/core/management/__init__.py", line 354, in execute_from_command_line utility.execute() File "/Library/Python/2.7/site-packages/django/core/management/__init__.py", line 328, in execute django.setup() File "/Library/Python/2.7/site-packages/django/__init__.py", line 18, in setup apps.populate(settings.INSTALLED_APPS) File "/Library/Python/2.7/site-packages/django/apps/registry.py", line 115, in populate app_config.ready() File "/Library/Python/2.7/site-packages/django/contrib/admin/apps.py", line 22, in ready self.module.autodiscover() File "/Library/Python/2.7/site-packages/django/contrib/admin/__init__.py", line 24, in autodiscover autodiscover_modules('admin', register_to=site) File "/Library/Python/2.7/site-packages/django/utils/module_loading.py", line 74, in autodiscover_modules import_module('%s.%s' % (app_config.name, module_to_search)) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/Users/aronadaal/Projects/issue-tracker/exp/mytesttracker/manageissues/admin.py", line 3, in <module> ImportError: cannot import name Issue -
How to load different css styles with query string parameter in Django
urls.py: urlpatterns = [ # Examples: url(r'^/pageId=yeti$', home, name='home'), ] layout.html: if(pageId == 'yeti'): <link rel="stylesheet" type="text/css" href="{% static 'app/content/bootswatch/yeti/bootstrap.min.css' %}" /> <select class="form-control" id="themeLoader" onchange={% url '/pageId=yeti/' %}> <option value="Yeti">Yeti</option> </select> views.py: def home(request): """Renders the home page.""" pageId = "" if(request.GET.get('pageId')): pageId= "yeti" elif request.POST.get('pageId'): pageId = request.POST.get('pageId') return render( request, 'app/index.html', context = { pageId : pageId, 'title':'Home Page', 'year':datetime.now().year, } ) -
Image is not saved to database django rest framework
I am trying to upload an image with django rest framework here is my code: settings.py: """ Django settings for app project. Generated by 'django-admin startproject' using Django 1.10.3. For more information on this file, see https://docs.djangoproject.com/en/1.10/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.10/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.10/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'baz^+ip1ik4_fla*zg$9q#37e(5jg6tmnwzj4btqw@nw=si)+(' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True # CSRF_COOKIE_SECURE = False ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'User.apps.UserConfig', 'image', 'rest_framework', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', #'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'app.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], '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', ], }, }, ] WSGI_APPLICATION = 'app.wsgi.application' REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ('rest_framework.permissions.AllowAny',), } # Database # https://docs.djangoproject.com/en/1.10/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'ImageSearchDB', 'USER': 'root', 'PASSWORD': '1234', 'HOST': 'localhost', 'PORT': '', 'OPTIONS': { 'init_command': 'SET default_storage_engine=INNODB', } } } … -
Passing URL Django Pattern in Datatables Column
I'm trying to pass a url into the "Guest Name", where the user clicks on the user and a modal will pop up that displays a form that you can input/view information related to that particular guest. I've tried fooling around with the render function, but haven't had much success. If I were to be doing this purely in Django, I would want the equivalent of {% 'namespace:guest_data_form' guest.pk %}, which would call a view to render the form within a modal. How would I accomplish the same within datatables? <script type="text/javascript" language="javascript" class="init"> $(document).ready(function() { $('#example').DataTable( { autoWidth: true, ajax: { url: "{% url 'guest_data_api' guest.id %}" }, columns: [ { "data" : "Room Number" }, { "data" : "Occupancy" }, { "data" : "Guest Name" }, { "data" : "Check In" }, { "data" : "Check Out" } ], "columnDefs": [ { "width": "15%", "targets": 2 } ] } ); } ); </script> -
Getting Http403 when saving files through django s3 middleware (but can save using boto in shell)
I have been trying to save user uploaded files to my s3 bucket via my django application. I'm using the django-s3-storage middleware, but I keep getting: S3ResponseError: 403 Forbidden (Access Denied) I'm using these settings: MEDIAFILES_LOCATION = 'media' AWS_S3_CUSTOM_DOMAIN = 'my-bucket.s3-website-eu-west-1.amazonaws.com' AWS_S3_HOST = 's3-website-eu-west-1.amazonaws.com' MEDIA_URL = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, MEDIAFILES_LOCATION) DEFAULT_FILE_STORAGE = 'django_s3_storage.storage.StaticS3Storage' #S3 settings from https://github.com/etianen/django-s3-storage AWS_ACCESS_KEY_ID = "xxx" AWS_SECRET_ACCESS_KEY = "yyy" AWS_S3_BUCKET_NAME = "my-bucket" AWS_S3_CALLING_FORMAT = "boto.s3.connection.OrdinaryCallingFormat" # Make user uploaded files public AWS_S3_BUCKET_AUTH = False AWS_S3_MAX_AGE_SECONDS = 60*60*24*365 # 1 year AWS_S3_GZIP = True And I know the credentials are valid: from boto.s3.connection import S3Connection from django.conf import settings conn = S3Connection(settings.AWS_ACCESS_KEY_ID, settings.AWS_SECRET_ACCESS_KEY) b = conn.get_bucket('my-bucket') key = b.get_key('test.txt') print(key.get_contents_as_string()) >>>this is a test from boto.s3.key import Key k = Key(b) k.key = 'test2.txt' k.set_contents_from_string('another test') >>>12 I've set a completely open CORS policy too (while trying to get this working from my dev machine): <?xml version="1.0" encoding="UTF-8"?> <CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/"> <CORSRule> <AllowedOrigin>*</AllowedOrigin> <AllowedMethod>PUT</AllowedMethod> <AllowedMethod>POST</AllowedMethod> <AllowedMethod>DELETE</AllowedMethod> <AllowedMethod>GET</AllowedMethod> <MaxAgeSeconds>3000</MaxAgeSeconds> <AllowedHeader>Authorization</AllowedHeader> </CORSRule> </CORSConfiguration> So what's stopping me authenticating via the middleware? (Or what else could be causing the 403?) -
Risks of using Docker in production
Consider I successfully created a Docker machine on DigitalOcean running some containers. Suppose that the local computer with which I configured the machine is gone (exploded, burnt, vaporized). How can I recover all the configuration files to reconnect to the machine? Docker is great, but it seems to lack of some really basic stuff: https://github.com/docker/machine/issues/1328 I am quite concerned of using it for production if all the management tools are bound to one local physical device. Maybe I am missing something, that is too strange to be true, but all the documentation I have found does not cover anything about this argument. -
Online Code Editors - Code Fights and Code Wars - Django
How can I have a code editor in my Django project like the editors used in sites like codefights and code wars?