Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Display calendar with all its events in django-schedule
How do I display the calendar with events for one particular day using django-schedule ? -
no module name 'celery' after migrate
I have been following tutorial how to import celery and run rabbitmq to my django project. and I have been following a tutorial on youtube. I do not now what I have missed but after the part where i ran python manage.py migrate djcelery it gives the result of: root@1095ea233e7b:/app/main# python3 manage.py migrate djcelery Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python3.4/dist-packages/django/core/management/__init__.py", line 353, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.4/dist-packages/django/core/management/__init__.py", line 302, in execute settings.INSTALLED_APPS File "/usr/local/lib/python3.4/dist-packages/django/conf/__init__.py", line 55, in __getattr__ self._setup(name) File "/usr/local/lib/python3.4/dist-packages/django/conf/__init__.py", line 43, in _setup self._wrapped = Settings(settings_module) File "/usr/local/lib/python3.4/dist-packages/django/conf/__init__.py", line 99, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/lib/python3.4/importlib/__init__.py", line 109, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 2254, in _gcd_import File "<frozen importlib._bootstrap>", line 2237, in _find_and_load File "<frozen importlib._bootstrap>", line 2226, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 1200, in _load_unlocked File "<frozen importlib._bootstrap>", line 1129, in _exec File "<frozen importlib._bootstrap>", line 1471, in exec_module File "<frozen importlib._bootstrap>", line 321, in _call_with_frames_removed File "/app/main/actinbox/settings.py", line 6, in <module> import djcelery this is the tutorial that I have been following: Django Celery Part 1 -
Faster HSTORE top-value for tag query
I have a model which holds key-value items in an HStore DictionaryField(). from django.contrib.gis.db import models from django.db.models import fields from django_hstore import hstore class Feature(models.Model): feature_id = models.BigIntegerField(default=0) point = models.PointField(srid=4326, geography=True, blank=True, null=True) geoobjects = models.GeoManager() tags = hstore.DictionaryField() tagmanager = hstore.HStoreGeoManager() user = models.CharField(max_length=200) feature_type = models.CharField(max_length=18) I want to find the most frequent value for a given tag in tags for Features with a specific user. Right now, I'm doing this: # poi nuples = ob.values_list('tags').filter( \ Q(tags__contains=['amenity']) & \ Q(feature_type='node') & \ Q(user='Max')) nalues = [] for tuple in nuples: try: str = tuple[0][0].get('amenity') if str: nalues.append(str) except Exception, e: pass print(Most_Common(nalues)) My Most_Common() function is a slight modification of the one found here. # finds the most common word in a list def Most_Common(lst): if not lst: return "" data = Counter(lst) return data.most_common(1)[0][0] I've read all of the Django HStore documentation, and while I've found a lot of stuff on how to filter objects by HStore contents, I have not found anything on how best to filter HStore contents by object properties. While my code seems to be working, it's very slow, and I'd like to improve efficiency. It seems unnecessary to me … -
Add language to LANGUAGES django/python
I am using Django 1.10 and Python 3.5. How do I add en-ca Canada English to the {{ LANGUAGES }}? This is the code I have used to temporarily display the available languages, just so I can see the languages: {% for lang in LANGUAGES %} {{ lang }}<br /> {% endfor %} The only English languages in the list are: ('en', 'English') ('en-au', 'Australian English') ('en-gb', 'British English') I am wanting to add English Canada as I must set the selected value to a language select list on the landing page. -
cookies not working in django
I have to set cookies to save cart details in my project but its not working, when i test cookies using function request.session.set_test_cookie() Then it set cookies but response.set_cookie function is not setting cookies. I have tried this code. def index(request): if request.method == 'GET': response = HttpResponse('hello') days_expire = 7 max_age = days_expire * 24 * 60 * 60 response.set_cookie('my_cookie', 'Product Cart', max_age=max_age) return render(request, 'home/index.py') and for getting cookis , this code is being used def sport(request): if request.method == 'GET': if 'my_cookie' in request.COOKIES: value = request.COOKIES['my_cookie'] return HttpResponse(value) else: return HttpResponse('Cookie not set') It always prints cookie not set string, What can be the reason behind it. -
Annotate django GeoQueryset with ST_X
I have a model looking like: from django.contrib.gis.db import models class Observation(models.Model): geometry = models.PointField() active = models.BooleanField(default=True) I want to convert the following SQL query to django ORM: SELECT id, ST_X(geometry) from observation; Following this answer, I have written: from django.db.models import Func obs = Observation.objects.filter( geometry__isnull=False, active=False ).annotate( x = Func("geometry", function="ST_X") ).values("id", "x") but got the error: TypeError: Improper geometry input type: <type 'float'> What can I do? NB: I am using Django==1.9.10 -
How to filter against multiple values for FK using DjangoFilterBackend
I have model with following fields: loading_port discharge_port carrier supplier All these fields are FK to models that contains name field. Also I have viewset, which uses DjangoFilter backend for filtering. At this moment I want to make possible filtering multiple values for each field, like: loading_port__name=PORT_1&loading_port__name=PORT_2&supplier__name=SUPP_NAME_1&supplier__name=SUPP_NAME_2 and so on. However if I actually pass this url it returns rows that filters against last parameter value (in this example for loading_port - PORT_2, for supplier - SUPP_NAME_2). How can I fix filtering so it will meet my requirements? -
Django savepoint rollback on catching an Integrity Error causes a TransactionManagementError
I am running the following code inside a transaction.atomic block in Django. @transaction.atomic() def test(): a.save() sid = transaction.savepoint() try: b.save() transaction.savepoint_commit(sid) except IntegrityError as e: transaction.savepoint_rollback(sid) c.save() This code gives me the following Error - TransactionManagementError An error occurred in the current transaction. You can't execute queries until the end of the 'atomic' block. I followed the following link from the official documentation. https://docs.djangoproject.com/en/1.10/topics/db/transactions/#s-savepoint-rollback What am I missing here. Urgent help required. -
embedded mode of mod_wsgi with virtualenv
First, I didn't have problem to work with daemon mode of mod_wsgi. I wanted to use embedded mode of mod_wsgi with virtualenv. The reason why I wanted to use embedded mode is to use apache basic or digest authentication with mod_wsgi. 1.error because low version of mod_wsgi If you install libapache2-mod-wsgi-py3 by apt-get in ubuntu 14 or 16, version of it is 3.4 according to this link, mod_wsgi version 4.2+ is needed for python 3.4. I installed mod_wsgi 4.5.7 following instructions in that link. no more error. 2.error with WSGIPythonPath I followed instructions in django doc. I kept making an error and I figured out that it doesnt work with virtualenv. I found this article. I thought this is a way to solve my problem but it still doesn't work. I can't understand why it doesn't work and can't find better resource than links I mentioned. <VirtualHost *:80> WSGIScriptAlias / /home/cango/myproject/myproject/wsgi.py WSGIPythonPath home/cango/myvenv/lib/python3.5/site-packages # I also tried /home/~ I put / at very beginning. It didn't work too. <Directory /home/cango/myproject/myproject> <Files wsgi.py> Require all granted </Files> </Directory> </VirtualHost> but if I change little bit to use daemon mode like below, it works! <VirtualHost *:80> WSGIDaemonProcess cango python-path=/home/cango/myproject:home/cango/myvenv/lib/Python3.5/site-packages WSGIProcessGroup cango WSGIScriptAlias … -
nginx test failing with different configuration file
I am trying to test why my nginx is failing to load, so I am running the command: nginx -c nginx.conf -t And getting the output: nginx: [emerg] open() "/usr/share/nginx/vehicles/nginx.conf" failed (2: No such file or directory) nginx: configuration file /usr/share/nginx/vehicles/nginx.conf test failed Which is weird, because it states a different configuration file then I provided. My configuration file: user www-data; daemon off; events { } http { ## # Logging Settings ## #access_log /logs/nginx_access.log; #error_log /logs/nginx_error.log; #upstream vehicles_server { # server unix:/tmp/server.sock #} server { listen 5001; server_name _; location / { proxy_pass unix:/server/server.sock; } } } I tried adding the error_logs but they didn't work as well. I am running the nginx using supervisord in an ubuntu docker container with gunicorn and Django as the web server (although I think they are completely unrelated to the problem) the file server.sock exists. Any ideas? -
Django bulk_create fails with DEFAULT_INDEX_TABLESPACE error
I’m trying to use bulk_create to make instances of my model. The traceback is File "/home/malikarumi/Projects/aishah/lib/python3.5/site-packages/django/db/models/fields/__init__.py", line 166, in __init__ self.db_tablespace = db_tablespace or settings.DEFAULT_INDEX_TABLESPACE File "/home/malikarumi/Projects/aishah/lib/python3.5/site-packages/django/conf/__init__.py", line 53, in __getattr__ self._setup(name) File "/home/malikarumi/Projects/aishah/lib/python3.5/site-packages/django/conf/__init__.py", line 39, in _setup % (desc, ENVIRONMENT_VARIABLE)) django.core.exceptions.ImproperlyConfigured: Requested setting DEFAULT_INDEX_TABLESPACE, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. My tablespace is pg_default malikarumi=> SELECT spcname FROM pg_tablespace; spcname ------------ pg_default pg_global (2 rows) And wsgi.py has: import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "jamf35.settings") runserver system checks comes up: System check identified no issues (0 silenced). November 18, 2016 - 06:23:48 Django version 1.10.2, using settings 'jamf35.settings' There was no mention of DEFAULT_INDEX_TABLESPACE in settings. Since it is supposed to be the default, I tried: DEFAULT_INDEX_TABLESPACE=’’ but that got the same error. You can use the DEFAULT_INDEX_TABLESPACE setting to specify a default value for db_tablespace. If db_tablespace isn’t specified and you didn’t set DEFAULT_INDEX_TABLESPACE, the index is created in the same tablespace as the tables. https://docs.djangoproject.com/en/1.10/topics/db/tablespaces/ I don’t understand why I am getting this error, and I am reluctant to set DEFAULT_INDEX_TABLESPACE if the default is already correct and in use. Besides, what am I supposed to do, … -
Unable to authenticate user from oracle database (python django)
I'm new with python django. I'm trying to create a simple apps that is the user login and connect it to Oracle 11g database. My connection is successful. My problem is when I use the user data (userid and password). It always redirect me on invalid page. It also pointing on the auth lines saying that (Expected :) error. Here's my code views.py from django.http import HttpResponse, HttpResponseRedirect from django.template import loader from django.contrib import auth from django.shortcuts import get_object_or_404, render from .models import OnlineUser def login(request): return render(request, 'login.html') def auth_view(request): userid = request.POST.get("userid", '') userpass = request.POST.get("userpass", '') user = auth.authenticate(OnlineUser.USERID=userid, OnlineUser.USERPASS=userpass) if user is not None: auth.login(request, user) return HttpResponseRedirect('/samplesite/loggedin') else: return HttpResponseRedirect('/samplesite/invalid') def loggedin(request): user = get_object_or_404(OnlineUser, pk=id) return render(request, 'login.html', {'user': user}) def invalid(request): return render(request, 'invalid.html') def logout(request): auth.logout(request) return render(request, 'logout.html') models.py from __future__ import unicode_literals from django.db import models class OnlineUser(models.Model): ID = models.IntegerField(primary_key=True) USERID = models.TextField() USERPASS = models.TextField() class Meta: managed = False db_table= 'TBL_ONLINE_USER' def __str__(self): return str(self.ID) templates/login.html <div> <form action="/samplesite/auth_view/" method="POST">{% csrf_token %} <input type='text' size='25' name="userid" id="userid" class="form-control" placeholder="User ID"/> <br/> <input type='password' size='25' name="userpass" id="userpass" class="form-control" placeholder="Password"/> <br/> <input type="submit" value="login"/> </form> </div> -
Could not find a version that satisfies the requirement pkg-resources==0.0.0
My app is deployed on heroku. When I push my code via git push heroku master. It gives me this error Collecting pkg-resources==0.0.0 (from -r requirements.txt (line 14)) remote: Could not find a version that satisfies the requirement pkg-resources==0.0.0 (from -r requirements.txt (line 14)) (from versions: ) remote: No matching distribution found for pkg-resources==0.0.0 (from -r requirements.txt (line 14)) remote: ! Push rejected, failed to compile Python app. requirement.txt amqp==2.1.1 billiard==3.5.0.2 boto==2.42.0 celery==4.0.0 dj-database-url==0.4.1 Django==1.10.2 django-appconf==1.0.2 django-model-utils==2.6 django-storages==1.5.1 djangorestframework==3.4.7 gunicorn==19.6.0 Jinja2==2.8 kombu==4.0.0 MarkupSafe==0.23 optional-django==0.1.0 pep8==1.7.0 pkg-resources==0.0.0 psycopg2==2.6.2 pyflakes==1.3.0 pytz==2016.7 rcssmin==1.0.6 requests==2.12.1 rjsmin==1.0.12 vine==1.1.3 whitenoise==3.2.2 Note: Its working perfectly fine on my local server. -
Django trying to use wrong Database User
I'm trying to connect my django project to an RDS MySQL database. I can connect fine using my credentials in MySQL Workbench and mysql command line, as well as simple scripts in the interpreter like this: connection = pymysql.connect(host='xxx.xx.us-west-2.rds.amazonaws.com', user='abc', password='password', db='playercomp', charset='utf8mb4', cursorclass=pymysql.cursors.DictCursor) I've set the AWS Security Group and VPC Security Group with All traffic | All | All | 0.0.0.0/0 Let's say my credentials are User: abc Password: password When I run python manage.py migrate it is attempting to login with Mike, not abc for some unknown reason (Mike is the Windows User). How do I prevent this? Attached is my settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'playercomp', 'USERNAME': 'abc', 'PASSWORD': 'password', 'HOST': 'xxx.xxx.us-west-2.rds.amazonaws.com', 'PORT': '3306', } } Error Trace: Traceback (most recent call last): File "manage.py", line 27, in <module> execute_from_command_line(sys.argv) File "C:\Users\Mike\Envs\playercomp\lib\site-packages\django\core\management\__init__.py", line 367, in execute_from_command_line utility.execute() File "C:\Users\Mike\Envs\playercomp\lib\site-packages\django\core\management\__init__.py", line 359, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\Mike\Envs\playercomp\lib\site-packages\django\core\management\base.py", line 294, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\Mike\Envs\playercomp\lib\site-packages\django\core\management\base.py", line 342, in execute self.check() File "C:\Users\Mike\Envs\playercomp\lib\site-packages\django\core\management\base.py", line 374, in check include_deployment_checks=include_deployment_checks, File "C:\Users\Mike\Envs\playercomp\lib\site-packages\django\core\management\commands\migrate.py", line 61, in _run_checks issues = run_checks(tags=[Tags.database]) File "C:\Users\Mike\Envs\playercomp\lib\site-packages\django\core\checks\registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "C:\Users\Mike\Envs\playercomp\lib\site-packages\django\core\checks\database.py", line 10, in check_database_backends issues.extend(conn.validation.check(**kwargs)) File … -
django_countries in django rest framework
I am trying to create an api which can return the all countires using django_countries. I am trying some thing following but it is not working. As an individual field it work fine but with complete countries list it is giving error. from django_countries import countries class CountrySerializer(serializers.Serializer): country = serializers.ListField(source=countries) class Meta: fields = ("country",) -
How to pass parameters from front end to python script
I'm trying to pass the parameters defined by a user in the front end to a python script being run on the server. I'm using a Django framework in the back end (probably too heavy for my purposes at the moment but wanted to give it a try). Here's the jQuery code I'm using to call the python fxn which is located at the defined url. The parameters I'd like to pass are in the data attribute. bbviz.onStart = (function() { $.ajax({ type:'get', url:'http://localhost:8000/statview/simulation/', data:{url:'blackch02', 'profile':'current', 'sims':1000}, async:'asynchronous', dataType:'json', success: function(data) { console.log(data); }, error: function(error) { console.log(error); } }); }); And here's the Django view function: def simulation(request): out = batterSim.sim_season(url, profile, sims) return out I'm calling the batterSim module and running the sim_season function which has the same named parameters as the data attribute. The function then returns a json object that the front end would receive. So I'm trying to figure out how to take those parameters from the ajax function and use them in the python function. -
Django handling pagination for dynamic order
I have done to query content and give as next_url, previous_url , etc. Problem is that query is based on dynamic sorting (just like Facebook newsfeed). How can I handle for following scenario ? User request page 1 and see article 10242. User haven’t request page 2 yet. Due to sorting algorithm, article 10242 will potentially moved to page 2. If so, when user request page 2, user will see duplicate post. I can't simply delete duplicate post on app. It will be okay for duplicate issue but let say when user request page 1, article 10333 is in page 2 but when user request page 2, article 10333 moves to page 1. Is there any recommended mechanism for pagination to support dynamic sorting? -
How to connect AWS RDS MySQL from Django app from local
I am able to connect to the RDS instance from both MySQL Workbench and the mysql CLI command, so it is not the credentials that are the issue. I am trying to run python manage.py migrate but I get the following output: Traceback (most recent call last): File "manage.py", line 27, in <module> execute_from_command_line(sys.argv) File "C:\Users\Mike\Envs\playercomp\lib\site-packages\django\core\management\__init__.py", line 367, in execute_from_command_line utility.execute() File "C:\Users\Mike\Envs\playercomp\lib\site-packages\django\core\management\__init__.py", line 359, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\Mike\Envs\playercomp\lib\site-packages\django\core\management\base.py", line 294, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\Mike\Envs\playercomp\lib\site-packages\django\core\management\base.py", line 342, in execute self.check() File "C:\Users\Mike\Envs\playercomp\lib\site-packages\django\core\management\base.py", line 374, in check include_deployment_checks=include_deployment_checks, File "C:\Users\Mike\Envs\playercomp\lib\site-packages\django\core\management\commands\migrate.py", line 61, in _run_checks issues = run_checks(tags=[Tags.database]) File "C:\Users\Mike\Envs\playercomp\lib\site-packages\django\core\checks\registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "C:\Users\Mike\Envs\playercomp\lib\site-packages\django\core\checks\database.py", line 10, in check_database_backends issues.extend(conn.validation.check(**kwargs)) File "C:\Users\Mike\Envs\playercomp\lib\site-packages\django\db\backends\mysql\validation.py", line 9, in check issues.extend(self._check_sql_mode(**kwargs)) File "C:\Users\Mike\Envs\playercomp\lib\site-packages\django\db\backends\mysql\validation.py", line 13, in _check_sql_mode with self.connection.cursor() as cursor: File "C:\Users\Mike\Envs\playercomp\lib\site-packages\django\db\backends\base\base.py", line 231, in cursor cursor = self.make_debug_cursor(self._cursor()) File "C:\Users\Mike\Envs\playercomp\lib\site-packages\django\db\backends\base\base.py", line 204, in _cursor self.ensure_connection() File "C:\Users\Mike\Envs\playercomp\lib\site-packages\django\db\backends\base\base.py", line 199, in ensure_connection self.connect() File "C:\Users\Mike\Envs\playercomp\lib\site-packages\django\db\utils.py", line 94, in __exit__ six.reraise(dj_exc_type, dj_exc_value, traceback) File "C:\Users\Mike\Envs\playercomp\lib\site-packages\django\db\backends\base\base.py", line 199, in ensure_connection self.connect() File "C:\Users\Mike\Envs\playercomp\lib\site-packages\django\db\backends\base\base.py", line 171, in connect self.connection = self.get_new_connection(conn_params) File "C:\Users\Mike\Envs\playercomp\lib\site-packages\django\db\backends\mysql\base.py", line 263, in get_new_connection conn = Database.connect(**conn_params) File "C:\Users\Mike\Envs\playercomp\lib\site-packages\pymysql\__init__.py", line 90, in Connect return Connection(*args, **kwargs) File "C:\Users\Mike\Envs\playercomp\lib\site-packages\pymysql\connections.py", … -
Django Rest Framework - Router Register not working
I'm using django rest framework to generate an api. In it I have two models, associated views and serializers. These are beers and pours. The beers api endpoint works as expected, but whenever I try to access the pours endpoint I get the following error: Could not resolve URL for hyperlinked relationship using view name "pours-detail". You may have failed to include the related model in your API, or incorrectly configured the 'lookup_field' attribute on this field. I'm not quite sure what I am doing wrong, can someone point out the error? models.py from __future__ import unicode_literals from django.db import models from django.utils import timezone class Beers(models.Model): """ Beers """ # The unique id id = models.AutoField(primary_key=True) # Timestamps created_at = models.DateTimeField(default=None, null=True) updated_at = models.DateTimeField(default=None, null=True) tap = models.PositiveIntegerField(default=None, null=True) url = models.CharField(max_length=255, default=None, null=True) abv = models.DecimalField(default=None, null=True, decimal_places=2, max_digits=3) style = models.CharField(max_length=255, default=None, null=True) score = models.PositiveIntegerField(default=None, null=True) tap_date = models.PositiveIntegerField(default=None, null=True) size = models.PositiveIntegerField(default=None, null=True) def save(self, *args, **kwargs): """ On save, update timestamps """ # If the record does not currently exist in the database self.created_at = timezone.now() self.updated_at = timezone.now() return super(Beers, self).save(*args, **kwargs) class Meta: db_table = 'beers' index_together = [("tap", "tap_date")] class … -
Django: Cannot retrieve cookies
I am not able to retrieve the cookies that I set in Signin_Auth view function. If the cookies are successfully set, the page will redirect to Main Page. But it didn't redirect, I have tried to catch the cookies in Main Page view function. It returned "None". However, after I clear browser's cache and cookies, I am able to retrieve the cookies. This happened to IE, Google Chrome and Firefox. What is happening? I have browse through most of the questions in Stackoverflow, but none of the answers can solve my case. As below are my view functions. def SignIn(request, template_name): #To load Login page .... code here return render(request, template_name, context) @csrf_exempt def Signin_Auth(request, template_name): #POST method, When user clicked Login button. context = {} context["Message"] = "" jsonData = json.dumps(context) response = HttpResponse(jsonData, content_type='application/json') response.set_cookie('UserName', request.POST['input_userName']) response.set_cookie('ID', request.POST['input_password']) return response After that, the login page will redirect to Main page at login page's javascript. Angularjs code: $scope.LoginBtn = function(input_userName, input_password){ if (input_userName != null && input_password != null) { $scope.spinner = true; document.getElementById("submitButton").disabled = true; var dataObject = { input_userName: input_userName, input_password: input_password }; $http({ url: "Signin_Auth", method: "POST", data: $.param(dataObject) }) .then(function(response){ $window.location.href = '/MainPage'; ##Redirect to … -
Is this Django model schema convenient?
Let's say a Bar can be in multiple Zipcodes. class State(models.Model): abbr = models.CharField(max_length=2) class City(models.Model): state = models.ForeignKey(State, related_name='cities') name = models.CharField(max_length=120) class Zipcode(models.Model): city = models.ForeignKey(City, related_name='zipcodes') value = models.CharField(max_length=5) class Bar(models.Model): name = models.CharField(max_length=120) zipcodes = models.ManyToManyField(Zipcode, related_name='bars') # cities = models.ManyToManyField(City, related_name='bars') # states = models.ManyToManyField(State, related_name='bars') Use case #1 # Duff zipcodes >>> bar = Bar.objects.get(name='Duff') >>> bar.zipcodes.all() And also, # 98101 bars >>> zipcode = Zipcode.objects.get(value='98101') >>> zipcode.bars.all() Then, if I need to get the bar cities I would do # Duff cities >>> City.objects.filter(zipcodes__bars=bar).distinct() # ouch? or maybe a property in Bar, class Bar(models.Model): ... @property def cities(self): return City.objects.filter(zipcodes__bars=self).distinct() >>> bar.cities.all() Adding "cities" m2m in Bar would be more direct? >>> bar.cities.all() However, why adding cities as m2m in Bar, if I already know the cities having the zipcodes? I would need to mantain both m2m relationships. i.e. If add a zipcode to a bar, I may have to add a city (related to that zipcode) to the bar cities. i.e. If I remove a zipcode from a bar, I may have to remove a city (related to that zipcode) from bar's cities. Use case #2 Let's say we want to know … -
Django Rest API Test Request Factory Content Empty
In the following test I get one of two errors, which I have not been able to resolve. This is my first project in Django, and therefore first time testing with it. I read that the APIRequestFactory will create its own database for the test then wipe it clean. There is no interaction with the middleware. Is it possible to check that the data is being retrieved properly using GET calls? So far I can only check that the status is 200 or not. The content of the GET or POST calls that I am making is empty. The examples that I have seen with the RequestFactory have not displayed any data comparssions. If you know of any examples, I should be able to resolve my problem. When created Report object is used to test against the data that was posted self.assertEqual(response.data['module'], report.module) TypeError: list indices must be integers, not str I am not sure what to change to make this assertion true. I have searched the error message, but it does not seem like I am using a ListField as report.module, since that is a direct field of the Report. When replacing report.module with the expected json data from … -
"DisallowedHost at /" django error
I am following this Digital Ocean tutorial for setting up my own Django server. Everything was going fine until I had to run the manage.py from port 8000 (all following the tutorial). When I ran the server everything was fine, but when I tried to visit the IP at that port, this error came up: DisallowedHost at / Invalid HTTP_HOST header: 'XXX.XXX.XXX.XXX:8000'. You may need to add u'XXX.XXX.XXX.XXX' to ALLOWED_HOSTS. (I dont want to show the actual IP, so I replaced them with Xs) So I want to know what I can do to fix it, but also why this is happening. I dont really know much about nginx or gunicorn, so I thought that following the tutorial would be fine, but guess not. Thanks for the help! -
prefetch_related() ForeignKey reverse lookup in Django?
I've got two models: class Company(models.Model): ... class Supplier(models.Model): company = models.ForeignKey(Company, null=True, related_name="suppliers") How to get all Companies with their related Suppliers? I've tried: Company.objects.prefetch_related('suppliers') Company.objects.prefetch_related('supplier_set') Company.objects.prefetch_related('suppliers').all() ... What I'm doing wrong? Thank you -
Change admin field filter name django 1.7 - ModelAdmin.list_filter
Basically I am try to create custom names for my filter fields as the original databse values dont hold much meaning. The current values are 0,1 and ?. I followed the django admin guide here https://docs.djangoproject.com/en/1.10/ref/contrib/admin/ on section ModelAdmin.list_filter. Below is my code: @admin.register(AuditPolicies) class AuditPoliciesAdmin(admin.ModelAdmin): list_filter = ('PolicyComparisonFilter', ) class PolicyComparisonFilter(admin.SimpleListFilter): title = _('Policy Comparisons') parameter_name = 'SourceState' def lookups(self, request, model_admin): """ Returns a list of tuples. The first element in each tuple is the coded value for the option that will appear in the URL query. The second element is the human-readable name for the option that will appear in the right sidebar. """ return ( ('0', _('No Match')), ('1', _('Match')), ('?', _('Missing')), ) def queryset(self, request, queryset): """ Returns the filtered queryset based on the value provided in the query string and retrievable via `self.value()`. """ # Compare the requested value (either '80s' or '90s') # to decide how to filter the queryset. if self.value() == '0': return queryset.filter(SourceState='0') if self.value() == '1': return queryset.filter(SourceState='1') if self.value() == '?': return queryset.filter(SourceState='1') And a couple of lines from my model(database): 364 STASH master-bi-prod-s3-ilayer-sen-group-user /master-bi-prod-s3-ilayer-sen-group-user.json 1 MASTER master-bi-prod-s3-ilayer-sen-group-user arn:aws:iam::588738232867:policy/master-bi-prod-s3-ilayer-sen-group-user 1 2016-11-17 04:04:16.117000 365 STASH master-bi-prod-s3-pop-admin /master-bi-prod-s3-pop-admin.json 0 MASTER …