Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
If I'm deploying a Django website with Nginx, do I need a service such as Digital Ocean on top of that?
I want to launch a website I've written in Python/Django. I want to host it on an Nginx Web Server. However I'm not sure if I need a service such as Digital Ocean or Heroku. What benefits do these services provide that I can't get with only Nginx? -
SECRET_KEY improperly configured in Apache(error log), but works in runserver
This is the full error django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty I develop in GNU/Linux(Arch) and deploy to Windows 10. Django's internal server runserver works in both environments, but Apache throws the above error in both environments. I have separate settings files in settings folder(package) with base.py, local.py and production.py. SECRET_KEY is set in base.py and both local.py and production.py import * from base.py. Earlier I tried an environment variable set in .bashrc like this export MYPROJECT_SECRET_KEY="very_long_fake_key" but simplified back to string version, but the problem persists. I deployed to pythonanywhere PAAS service and it worked there. -
Django hide all form field errors
Is there a straightforward way to hide all Django form field errors (preferably using CSS)? I ultimately want to hide them and then display my own custom errors. I have tried the code presented here: django hide all form errors but they still keep reappearing. Thanks! -
Trouble parsing orderddict in django template
I'm having trouble trying to parse an orderddict in my django template. This is an example dict: OrderedDict([ (u'header-1510123912515', '"{u\'label\': u\'label\'}"'), (u'input-1510215273074', '"{u\'label\': u\'Preferred Assignment Area\'}"'), (u'input-1510215283971', '"{u\'label\': u\'Expected Salary\'}"'), (u'input-1510215288135', '"{u\'label\': u\'Last Drawn Salary\'}"'), ]) From the above, I would want to get the content of label. This is how I'm currently going through the dict in the template: {% for form in document.forms.all %} {% for k,v in form.hdict.items %} {% if 'header' not in k %} {"key": {{k}}, "label": "{{v.label}}"}, {% endif %} {% endfor %} {% endfor %} I'm able to successfully get the key, but not the values part (label). I hope you can help me with this as I'm quite new to django. Thanks -
Does python2.7 support Chinese path?
The python2.7 do not support Chinese path? File "/Users/denghaibing/Desktop/Test/TestPython/testDemo02/apps/用户首页/ordermanage/api/views.py", line 11, in <module> from .serializers import OrderSerializer File "/Users/denghaibing/Desktop/Test/TestPython/testDemo02/apps/用户首页/ordermanage/api/serializers.py", line 46 from 用户后台.产品管理.productmanage.models import ( ^ SyntaxError: invalid syntax In my project: You see, I use two level Chinese directories to group my apps in my Test project. but this works in Python3.5, but if use the Python2.7 Interpreter, there will comes the SyntaxError: invalid syntax issue. It do not supports Chinese path. Is there a way to let Python2.7 support Chinese path? -
Error when reading csv: coercing to Unicode: need string or buffer
I am receiving the following error when I am reading a csv file in my Django project. coercing to Unicode: need string or buffer, file found I have searched the forum already, but could not find a solution to my problem. I also have no idea how to solve this. When I run this code locally I don't have the problem. Once I execute the script from my django views I get the error from above. coercing to Unicode: need string or buffer, file found import os from django.conf import settings path = os.path.join(settings.BASE_DIR, 'technicalAnalalysis/EUR_USD') def index(request): return render(request, 'technicalAnalysis/home.html') class carouselData(APIView): authentication_classes = [] permission_classes = [] def get(self, request, format=None): import csv EUR_USD_closeBid = [] with open(path) as csvfile: readCSV = csv.reader(open(csvfile), delimiter=str(',').encode('utf-8'), ) for row in readCSV: closeBid = row[0] BOP = row[12] EUR_USD_closeBid.append(closeBid) data = { "EUR_USD_closeBid":EUR_USD_closeBid, } return Response(data) this is how the csv was created master.to_csv(eachCurrency, encoding='utf-8', index=False) and this how the csv data looks like 1.4551,2016-08-25T21:00:00.000000Z,1.46613370302,1.4588,1.45146629698,19.2623252118,16.0468541889,18.0294990319,52.3305843166,-0.000955558790503,0.00497888833433,0.00402332954383,-0.228110599078 1.45557,2016-08-28T21:00:00.000000Z,1.46022799941,1.45683,1.45343200059,18.3020335848,15.2573095743,17.1424034245,52.7163692506,-0.00105527020367,0.00471507078342,0.00365980057975,0.655172413793 1.45919,2016-08-29T21:00:00.000000Z,1.459965965,1.456766,1.453566035,17.7461955078,14.6233407849,18.0619294336,55.6907414516,-0.000874414835166,0.00449646707462,0.00362205223946,0.82183908046 Thanks a lot in advance and kind regards -
Got an error creating the test database: Django unittest
When I run python manage.py test, django is asking a strange question each time: $ python manage.py test Creating test database for alias 'default'... Got an error creating the test database: (1044, "Access denied for user 'nyble'@'localhost' to database 'test_nybledb'") Type 'yes' if you would like to try deleting the test database 'test_nybledb', or 'no' to cancel: I was expecting it to just delete and remake a basic sqlite3 DB, and I don't want this behavior. Whether I say yes or no it just exits tests: Destroying old test database for alias 'default'... Got an error recreating the test database: (1044, "Access denied for user 'nyble'@'localhost' to database 'test_nybledb'") In settings I have DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'nybledb', 'USER': 'nyble', 'PASSWORD': 'password', 'HOST': 'localhost', # Or an IP Address that your DB is hosted on 'PORT': '3306', } } How can I stop this and make it use normal sqlite3 db during running tests? Thank you -
Django IntegrityError-NOT NULL constraint failed: portfolio_myportfolio.holder_id
I am trying to make a portfolio manager app in django. I tried making the holder as a primary key. But in that case, the new entry overlaps the old one. So, I deleted that database and started afresh. Now, when I am trying to add a portfolio with a logged in user, I am getting the error as under:- IntegrityError-NOT NULL constraint failed: portfolio_myportfolio.holder_id I also wanted to set my database in such a way that If user adds the quantity of the same stock with same nsecode, it should add up in the previous entry instead of making a new row. In that case, what should be my scenario. Since, I am very new to python and django, my code is not clean and might have few lines of code, which is un-necessary, any help in removing such errors would be much appreciated. My Model is from django.db import models from django.contrib.auth.models import User codes=(tuple of tuples) class MyPortfolio(models.Model): nsecodes = models.CharField(max_length=10, choices=codes) quantity = models.PositiveIntegerField() buyvalue=models.DecimalField(max_digits=15,decimal_places=2) holder = models.ForeignKey(User, related_name='myportfolio') # Create your models here. my views. py is : from django.shortcuts import render,redirect,get_object_or_404 from django.views.generic.edit import CreateView from .models import MyPortfolio from .forms import AddNewForm from … -
Django /admin redirects to /usr/src/app/admin
We have our Django 1.9.6 application running in a Docker container. The docker container has nginx configured to serve the static files. We link to /admin and it will take us to the /admin pages but when we click a link it takes us to /usr/src/app/admin/api/module/ I can tell you Django is running from the directory /usr/src/app. We tried adding FORCE_SCRIPT_NAME='' to the settings and this has not helped. The Django app is running via Daphne (as we are using Channels) Here is our nginx config: server { listen 80 default_server; charset utf-8; # max upload size client_max_body_size 4G; # Django media location /media { alias /usr/src/app/media; } location /static { alias /usr/src/app/static-collect; - amend as required } location / { proxy_pass http://0.0.0.0:8000; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $server_name; } }` -
Wrong formation of static links in template django
I deployed my Django app using nginx and works fine. But my images doesn't load in pages. Not is problem with static folder, because favicon and css and js files loaded sucessfully. I take a look in a source code formed in webbrowser and i saw that the images have a '/' in the end of link. This is making the address invalid. If a remove manually the '/' i found the resource in site. But i don't know what is causing the insertion this caractere. My sites-available file server { listen 80; server_name localhost; location = /favicon.ico {access_log_off; log_not_found off;} location /static/ { root /home/pi/WebSite; } location / { include proxy_params; proxy_pass http://unix:home/pi/WebSite/Website.sock; } } My settings.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR,'static/') My template file: <div class='col-md-12 col-xs-12'> <img class="img-rounded img-responsive text-center" src = {% static 'img/sistema.png' %}/> <img class="img-rounded img-responsive text-center" src = {% static 'img/legenda.png' %}/> </div> In the source code of the site, the images appears: <div class='col-md-12 col-xs-12'> <img class="img-rounded img-responsive text-center" src = /static/img/sistema.png/> <img class="img-rounded img-responsive text-center" src = /static/img/legenda.png/> </div> Any ideas, sugestions? Thanks a lot, i no more ideas -
how template POST parameter to view?
Hi~ o( ̄▽ ̄)ブ ,I have a question about django template POST value to view.I have done this: A button passes a unique value to a view's function. and now I want to get this: the left button pass values to the function_1,and the right button pass values to the function_2. when I click one button, only the value passes to the corresponding function.How I change the ajax code and how to get it from view's function? please and thanks! -
How can I pass values/parameters from HTML to Django Views?
I would usually do this in ajax I think. But if for example I have a button and a search input box that will have a query value, how can I pass the search value (and possibly multiple values/parameters that is not obtained through a form field) to Django views on button click to the url? HTML <div> <input id="search" name="search" type="text" class="query-search" placeholder="Search..."> <button onclick="window.location={% url 'view' %};" type="button" class="btn btn-primary">View Details</button> </div> Views def view_detail(request): ... <How to get values from HTML without using ajax? Or its the only way?> URLs url(r'^view/', views.view_detail, name='view_detail') -
How to open and read a csv file in django views.py
I would like to open and read a csv file in my django project. On my local directory everything works. But once I migrate the codes to my django project I get the following error. [Errno 2] No such file or directory: u'EUR_USD' The csv file is in exactly the same directory as the views.py and everything is set up just as in my local project but it still does not work. Likewise, I have tried to move the file into the static directory of the app but it still does not work. Does someone have a solution to my problem? Help is much appreciated. Thanks and kind regards. class carouselData(APIView): authentication_classes = [] permission_classes = [] def get(self, request, format=None): import csv EUR_USD_closeBid = [] with open('EUR_USD') as csvfile: readCSV = csv.reader(csvfile, delimiter=',') for row in readCSV: closeBid = row[0] EUR_USD_closeBid.append(closeBid) data = { "EUR_USD_closeBid":EUR_USD_closeBid } return Response(data) -
Can I use Django REST with custom structures on serializers?
I have a project in which I would like to be able to create a serializer that isn't based on a model and that could accept a custom structure of my choice. Example: class OptionSerializer(serializers.Serializer): option_1 = serializers.IntegerField() option_2 = serializers.IntegerField() option_3 = serializers.IntegerField() option_4 = serializers.IntegerField() option_5 = serializers.IntegerField() class Meta: fields = ('option_1', 'option_2', 'option_3', 'option_4', 'option_5') class QuestionsSerializer(serializers.Serializer): questions = OptionSerializer(data=[], many=True) class Meta: fields = ('questions',) In this example, I would have a custom object called Questions that would have an array of objects, each one containing the keys 'option_1', 'option_2', 'option_3', 'option_4' and 'option_5'. My goal would be to use something like this in a GenericAPIView that would allow me to render a similar structure when attempting a POST operation with the browsable API, and also to minimize validation efforts. Is that possible to be done? -
Join Many to Many tables in Django
I have three models, connected with many to many relationships ModelA - M:N - Model B - M:N - Model C They are defined as ModelA attA1 attA2 ModelB attB1 att1s.ManyToManyField(ModelA) att3s.ManyToManyField(ModelC) ModelC attC1 attC2 I want to store the data from these three on server start, without querying the database again - but I need all the data in each table. The equivalent SQL for what I'm looking for is: SELECT * FROM ModelA, ModelB, ModelC WHERE ModelA.pkA = ModelB.pkA AND ModelC.pkC=ModelB.pkC Any help would be much appreciated! -
In Django, how to re-package a Request.response as a Django response?
I have a Django App that accepts messages from a remote device as a POST message. This fits well with Django's framework! I used the generic View class (from django.views import View) and defined my own POST function. But the remote device requires a special reply that I cannot generate in Django (yet). So, I use the Requests library to re-create the POST message and send it up to the manufacturer's cloud server. That server processes the data, and responds with the special message in the body. Idealy, the entire HTML response message should go back to the remote device. If it does not get a valid reply, it will re-send the message. Which would be annoying! I've been googling, but am having trouble getting a clear picture on how to either: (a): Reply back in Django with the Requests.response object without any edits. (b): Build a Django response and send it back. Actually, I think I do know how to do (b), but its work. I would rather do (a) if its possible. Thanks in Advance! Rich. -
Revert objects on site instead of admin using django simple history
I have employed django simple history package on the admin site to be able to track and revert to previous versions of the object of the model. I am designing a web form that allows users to change instances of the model object using model form on django and would like to allow the users to view and revert to previous versions. Also to allow them to see what are the changes compared to the current version. With the code below I am able to get the list of historical records on my template under histoire. class CompanyDetailView(LoginRequiredMixin,generic.DetailView): model = Company def get_context_data(self, **kwargs): context = super(CompanyDetailView, self).get_context_data(**kwargs) company_instance = self.object context['histoire'] = company_instance.history.all() return context In my template, <p> Previous versions: {% for item in histoire %} <li> {{ item }} submitted by {{ item.history_user }} {{ item.history_object }} </li> {% endfor %} </p> But ideally I want item.history_object to be a link that users can view the previous object and be able to revert if desired. -
Django - How to call a session in a module different than views.py?
I'd like to call a session that was set at views.py in my forms.py. Is that possible? I tried to do that but I faced some issues with 'request'. forms.py from django import forms class exampleform(forms.Form): a = 'test' # I would like to replace this 'test' by a data stored in a session set in views.py options_list = [ (a, a), ('b', 'b'), ('c', 'c'), ] options_form = forms.ChoiceField(required=False, choices=options_list,widget=forms.RadioSelect(attrs={'class':'example_form'}), label='') views.py from django.shortcuts import render from .forms import exampleform def example(request): option_a = '123' request.session['my_session'] = option_a form = exampleform context = { 'form': form, } return render(request, 'example/index.html', context,) I don't try to import the value instead of make a session, because this value will be created inside the same view that I call the form. Therefore I would get a circular error. I hope that to store this value in a session, and then send it to my form will not raise this circular issue. P.S. I'm a beginner on programming. -
Resolving Fatal status in Supervisor and Django
I am using Digital Ocean Ubuntu server to deploy my Django project and follow this guide to set it all up: A Complete Beginner's Guide to Django - Part 7 I am the process of configurig Gunicorn and Supervisor and I get the following error: I am logged in as non-root but sudo user that I have created called betofolio. My django project is called betofolio. Below is a screenshot of what my folders look like: Following the steps from the tutorial: Create a new file named gunicorn_start inside /home/betofolio: vim gunicorn_start I insert the following: #!/bin/bash NAME="betofolio" DIR=/home/betofolio/betofolio USER=betofolio GROUP=betofolio WORKERS=3 BIND=unix:/home/betofolio/run/gunicorn.sock DJANGO_SETTINGS_MODULE=betofolio.settings DJANGO_WSGI_MODULE=betofolio.wsgi LOG_LEVEL=error cd $DIR source ../venv/bin/activate export DJANGO_SETTINGS_MODULE=$DJANGO_SETTINGS_MODULE export PYTHONPATH=$DIR:$PYTHONPATH exec ../venv/bin/gunicorn ${DJANGO_WSGI_MODULE}:application \ --name $NAME \ --workers $WORKERS \ --user=$USER \ --group=$GROUP \ --bind=$BIND \ --log-level=$LOG_LEVEL \ --log-file=- Then I save and exit. Make this file executable: chmod u+x gunicorn_start Create two empty folders, one for the socket file and one to store the logs: mkdir run logs Configuring Supervisor Create an empty log file inside the /home/betofolio/logs/ folder: touch logs/gunicorn.log Now create a new supervisor file: sudo vim /etc/supervisor/conf.d/betofolio.conf [program:betofolio] command=/home/betofolio/gunicorn_start user=betofolio autostart=true autorestart=true redirect_stderr=true stdout_logfile=/home/betofolio/logs/gunicorn.log Then: sudo supervisorctl reread sudo supervisorctl update Now … -
Django run background script using subprocess, passing primary key to script to retrieve object
I have been figuring on how to run a script on background, so that i can process an object without having the user to wait for the server to respond. Right now, I have come across subprocess, however, I couldn't figure how to pass the primary key of the object to the script, so that the background script could retrieve the object from within it. Views.py import subprocess, sys def allocate_request(request, event_id): event = get_object_or_404(MeetingEvent, id=event_id) subprocess.Popen([sys.executable, 'sorting.py', str(event_id)], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) return HttpResponse("Request Submitted.") and in the same directory, Sorting.py import sys class Organize: #... try: event_id = sys.argv[2] event = MeetingEvent.objects.get(id=event_id) Organize(event=event) except MeetingEvent.DoesNotExist: pass except IndexError: pass but it seems like sub script isn't able to fetch the primary key argument, neither i could pass the check using django's console. I wonder what is wrong with my code. Would appreciate any help :) -
could not translate host name "postgres" to address
I use PostreSQL and Django 1.8 in my app. I have an error: django.db.utils.OperationalError: could not translate host name "postgres" to address: nodename nor servname provided, or not known but I cannot find a please where host name "postgres" is set, because I have set host name to localhost. DATABASE_USER = MY_DATABASE_USER = admin DATABASE_HOST = MY_DATABASE_HOST = localhost DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'default_db', 'USER': os.getenv('DATABASE_USER', ''), 'PASSWORD': os.getenv('DATABASE_PASSWORD', ''), 'HOST': os.getenv('DATABASE_HOST', ''), 'PORT': '5432', }, 'my_db': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': os.getenv('MY_DATABASE_NAME', 'my_dev'), 'USER': os.getenv('MY_DATABASE_USER', os.getenv('DATABASE_USER', 'admin')), 'PASSWORD': os.getenv('MY_DATABASE_PASSWORD', os.getenv('DATABASE_PASSWORD', '')), 'HOST': os.getenv('MY_DATABASE_HOST', os.getenv('DATABASE_HOST', '')), 'PORT': '5432', } } Can I fix that error? -
Django Fixtures and Test Server
Okay so I've run into an interesting testing problem. One of my apps uses a MYSQL FULLTEXT index which I have to create manually since I can't specify it on my model creation. This works fine, except now it's created a problem testing. My test routine loads up the data using Fixtures, but it won't create the Index so my search functions fail. I can create the index manually but everytime I try to run manage.py testserver, it recreates the database so I lose the index. Is there a way I can integrate my function so that it is run anytime the databases are recreated? -
Django, Elasticsearch and maybe Haystack
I am trying to use Elasticsearch to provide good search capabilities to a Django project. This is not a technical question, but I would rather hope that you can provide insight into my situation and help me choose the right approach, wether you have experience with the technologies discussed below or based on some best practices of development in general. My environment is kind of complex and there is a lot of compatibility issues that should be taken into consideration. I will spare you the details, but here are some constraints that should be kept in mind: I have to use the version 5 of Elasticsearch Haystack is only compatible with the versions 1 and 2 of Elasticsearch Synchronization of DB and Elasticsearch should be near real-time, meaning I can't use a cron job, and that a latency of a minute is tolerable. I have messed around with the Python Elasticsearch client and its more high-level version Elasticsearch DSL. They worked when it comes to inserting, retrieving data... from Elasticsearch. I also tried using Haystack to integrate Elasticsearch into my project. More specifically I successfully used celery-haystack to handle the synchronization between the database and Elasticsearch. Even though the celery-haystack … -
routing with django and AngularJS
I new to AngularJS and trying to set up Django with AngularJs, however, I have some issues with handling the routing with those two frameworks. so far I've set up like below: When I run http://localhost:8000/index.html it works and shows me the file, but when I run http://localhost:8000/test as I wrote in app.js it gives me standard Django 404 error. What am I missing? urls.py urlpatterns = [ url(r'^index.html/$', ] app.js var app = angular.module("myApp", ["ngRoute"]); app.config(function($routeProvider) { $routeProvider .when("/test", { templateUrl : "index.html", controller: "MainCtrl" }) }); app.controller("MainCtrl", function ($scope) { $scope.msg = "test"; }); index.html {% load static %} <html ng-app="myApp"> <head> </head> <body> <div> test </div> <script src="{% static 'js/general/angular.min.js' %}" type="text/javascript"></script> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular-route.js"></script> <script type="text/javascript" src="{% static 'js/app.js' %}"></script> </body> </html> -
'function' object has no attribute '_meta' inlineformset_factory django
I'm trying to create a form that submits a model with a foreign key but i got this error : Traceback (most recent call last): File "C:\Users\~\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\handlers\exception.py", line 41, in inner response = get_response(request) File "C:\Users\~\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\~\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\~\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\views\decorators\csrf.py", line 58, in wrapped_view return view_func(*args, **kwargs) File "~.py", line 21, in wrap return function(request, *args, **kwargs) File "~.py", line 32, in wrap return function(request, *args, **kwargs) File "~.py", line 428, in example PostFormSet = inlineformset_factory(User, Post, fields=('longitude', 'latitude', 'placename', 'explanation', )) File "C:\Users\~\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\forms\models.py", line 1038, in inlineformset_factory fk = _get_foreign_key(parent_model, model, fk_name=fk_name) File "C:\Users\~\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\forms\models.py", line 980, in _get_foreign_key opts = model._meta AttributeError: 'function' object has no attribute '_meta' model.py class Post(models.Model): owner = models.ForeignKey(User,on_delete=models.CASCADE,related_name="posts",blank=False,null=False) </other fields>... class PostImage(models.Model): owner = models.ForeignKey(Post,on_delete=models.CASCADE,related_name="images",blank=False,null=False) views.py def example(request): context = { 'hellow we':"qfqf" } print(request.user) PostFormSet = inlineformset_factory(User, Post, fields=('longitude', 'latitude', 'placename', 'explanation', )) print("------------------------------------------------------------") print(frm.errors) return JsonResponse(context, encoder=JSONEncoder)