Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Generating unique random field in Django or PostgreSQL
I have this model class Inscription(models.Model): person = models.ForeignKey(Person) congress = models.ForeignKey(Congress) folio = models.IntegerField(max_length=4, editable=False) I need the folio attribute to be unique within the same congress, but repeatable in the table. Is there any way to achieve this? It doesnt matter if the work is to be done in Django or PostgreSQL Thank you for reading. -
Is ForeignKey concept a violation of SRP?
I'd like to illustrate the general nature of my question with a Django sample: class Person(models.Model): team = models.ForeignKey(Team, related_name='member', on_delete=models.CASCADE) class Team(models.Model): pass Here, the goal is to create a relationship representing the fact that a single person can be associated with one and only one team. But, doesn't it violate SRP that Person entity is aware of Team entity, and not vice-versa? I would rather write something like class Person(models.Model): pass class Team(models.Model): members = models.OneToMany(Person, related_name='team', on_delete=models.CASCADE) As a consequence, whenever a new Entity-to-Person relationship is introduced (or, an existing one wiped out) there'd be no need to update Person model. -
Connecting to Dynamics CRM database hosted in the "cloud" on Office 365
The company I work for uses Microsoft Dynamics CRM to track our clients and is hosted through Office 365. It has the most up-to-date client information. Up until now we have been maintaining a second database with duplicate data that is used for the internal database... as you might have guessed it doesn't get updated with the latest information, so we run into issues where a query is run and pulls out of date client information. Instead of queries using the internal database's client list, I want to pull the data from the CRM database. Has anyone done this before and have experience with it? Not finding much on it. The URL is something like https://businessname.crm.dynamics.com. Oh and I am using Django. -
Django Model._meta.get_fields() in decorator
I need access to model class fileds in decorator: from django.db import models class Register: REGISTRY = {} def __init__(self, name): self.name = name def __call__(self, cls): self.register(cls) return cls def register(self, cls): print(cls.__name__, '-', self.name) # prints: Item - Item registered print(cls._meta.get_fields()) # raises: django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet. @Register('Item registered') class Item(models.Model): title = models.CharField(max_length=200, verbose_name='Title') cls._meta.get_fields() raises: django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet. How to access fields? -
Django Application: Model ImportError
I have a django 1.9 application using DRF with the following folder structure - api/ - api/models.py - api/serializers.py - api/views.py - manage.py In serializers.py I have an import: from api.models import Model1, Model2, ... In views.py I have these imports: from api.serializers import NotificationSerializer from api.models import Model1, Model2, ... Everything works fine until now. But after adding from api.serializers import NotificationSerializer in models.py, django starts complaining when I start the dev server: File ".../api/serializers.py", line 3, in <module> from api.models import Model1, Model2,... ImportError: cannot import name Model1 I know that there must be a problem with the python import paths, but I can't figure it out. -
Extended django templates errors
I have very frequent problem with django "extends" tag. Suppose we have two files: "base.html" and "extended.html" So, if I have an error in template extended.html then in django error page I'll see something like In template /var/www/.../extended.html, error at line 0 In my case I have the error Need 3 values to unpack... go 2 but I can't fix it, because I can't find line where this error has ocсured And this could be much worse situation, if "extends" chain have more then one file! PS Debug Toolbar doesn't help I this case -
Unittest an AMP page
I'm trying to write a simple unittest to make sure my AMP-enabled pages load correctly. Here's the test: class TestAmpPageLoads(TestCase): def setUp(self): self.client = Client() self.amp_article = NewsPost(site_id=1, title="Amp Article", body="body", is_amp=True) self.amp_article.save() def test_amp_detail_page_loads(self): index_url = reverse("amp_news_detail", kwargs={"pk": self.amp_article.pk}) response = self.client.get(index_url) self.assertEqual(response.status_code, 200) The first time I ran it, it failed because the status_code was returning 301. I added follow=True to my GET request, and dropping into a pdb I found that the index_url was correctly evaluating as u'/amp/news/1/' and the redirect chain was [('http://testserver/news/amp-article/1/', 301)], which was surprising because that is the canonical URL, and I'm not sure why the test client is touching that at all. On top of that, when follow=True was included, the status code changed to 404, which is totally confusing as neither URL should have a problem. -
Getting Database is improperly configured .Please supply the name value error
I come across this question settings.DATABASES is improperly configured. Please supply the NAME value but it doesn't worked for me. On applying python manage.py makemigrations,I am getting the error Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/home/rishav/EvalAI/venv/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line utility.execute() File "/home/rishav/EvalAI/venv/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 359, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/rishav/EvalAI/venv/local/lib/python2.7/site-packages/django/core/management/base.py", line 294, in run_from_argv self.execute(*args, **cmd_options) File "/home/rishav/EvalAI/venv/local/lib/python2.7/site-packages/django/core/management/base.py", line 345, in execute output = self.handle(*args, **options) File "/home/rishav/EvalAI/venv/local/lib/python2.7/site-packages/django/core/management/commands/makemigrations.py", line 106, in handle loader.check_consistent_history(connection) File "/home/rishav/EvalAI/venv/local/lib/python2.7/site-packages/django/db/migrations/loader.py", line 276, in check_consistent_history applied = recorder.applied_migrations() File "/home/rishav/EvalAI/venv/local/lib/python2.7/site-packages/django/db/migrations/recorder.py", line 65, in applied_migrations self.ensure_schema() File "/home/rishav/EvalAI/venv/local/lib/python2.7/site-packages/django/db/migrations/recorder.py", line 52, in ensure_schema if self.Migration._meta.db_table in self.connection.introspection.table_names(self.connection.cursor()): File "/home/rishav/EvalAI/venv/local/lib/python2.7/site-packages/django/db/backends/base/base.py", line 233, in cursor cursor = self.make_cursor(self._cursor()) File "/home/rishav/EvalAI/venv/local/lib/python2.7/site-packages/django/db/backends/base/base.py", line 204, in _cursor self.ensure_connection() File "/home/rishav/EvalAI/venv/local/lib/python2.7/site-packages/django/db/backends/base/base.py", line 199, in ensure_connection self.connect() File "/home/rishav/EvalAI/venv/local/lib/python2.7/site-packages/django/db/backends/base/base.py", line 170, in connect conn_params = self.get_connection_params() File "/home/rishav/EvalAI/venv/local/lib/python2.7/site-packages/django/db/backends/postgresql/base.py", line 158, in get_connection_params "settings.DATABASES is improperly configured. " django.core.exceptions.ImproperlyConfigured: settings.DATABASES is improperly configured. Please supply the NAME value. My dev database DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'evalai', 'USER': 'rishav', 'PASSWORD': 'rishav', 'HOST': 'localhost', 'PORT': 5432, } } And the prod database DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': os.environ.get('RDS_DB_NAME', ""), 'USER': os.environ.get('RDS_USERNAME', ""), 'PASSWORD': os.environ.get('RDS_PASSWORD', … -
Django create and submit form manually
The question is that my form is dynamical. Every time there may be different number of fields depending on data in DB. I am able to render this form manually (by passing attributes and types to template as context). But how can I handle the action of pressing submit button in django? -
Serving static files using mod_wsgi-express with ProxyPass is not working
I found out mod_wsgi-express today and I think it is really cool project. I can't believe this single command is all needed to deploy Python/Django web applications. mod_wsgi-express start-server project/wsgi.py However, documentation seems to be still missing (or I didn't find?). As far as I see, it is not mentioned in official docs here. I am hosting couple of small sites on same machine, thus using VirtualHost. So I need to proxy it to another port like this: <VirtualHost *:80> ProxyPreserveHost On ServerName ombudsman.u9.uhura.de ProxyPass "/" "http://localhost:8000" </VirtualHost> So far so good. I am running mod_wsgi-express as follows: mod_wsgi-express start-server --url-alias /static /path/to/static project/wsgi.py You see, I am trying to set static files config in mod_wsgi-express itself. However, static files are not served and gives 502 Proxy Error. So proxying dynamic requests is working, but not static files. Site is also working file when accessed directly at port 8000. What am I missing here? -
How do I connect to MongoDB v2.6.12 from Django 1.10 (python3.4) and pymongo v3.4?
I am new to Django, and I set up a mysites app using the tutorial given here I followed this guide to setup mongodb with Django using mongoengine However, I keep getting the following error everytime I try running the server: (myVirtEnv_1) [root@sandbox1 django-mongoadmin]# python mysite/manage.py runserver 99 Traceback (most recent call last): File "/root/blrasp/myVirtEnv_1/lib/python3.4/site-packages/mongoengine/connection.py", line 124, in get_connection _connections[alias] = connection if connection else connection_class(**conn_settings) File "/root/blrasp/myVirtEnv_1/lib/python3.4/site-packages/pymongo/mongo_client.py", line 422, in __init__ for k, v in keyword_opts.items()) File "/root/blrasp/myVirtEnv_1/lib/python3.4/site-packages/pymongo/mongo_client.py", line 422, in <genexpr> for k, v in keyword_opts.items()) File "/root/blrasp/myVirtEnv_1/lib/python3.4/site-packages/pymongo/common.py", line 539, in validate value = validator(option, value) File "/root/blrasp/myVirtEnv_1/lib/python3.4/site-packages/pymongo/common.py", line 301, in validate_read_preference raise TypeError("%r is not a read preference." % (value,)) TypeError: False is not a read preference. During handling of the above exception, another exception occurred: Traceback (most recent call last): File "mysite/manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/root/blrasp/myVirtEnv_1/lib/python3.4/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line utility.execute() File "/root/blrasp/myVirtEnv_1/lib/python3.4/site-packages/django/core/management/__init__.py", line 316, in execute settings.INSTALLED_APPS File "/root/blrasp/myVirtEnv_1/lib/python3.4/site-packages/django/conf/__init__.py", line 53, in __getattr__ self._setup(name) File "/root/blrasp/myVirtEnv_1/lib/python3.4/site-packages/django/conf/__init__.py", line 41, in _setup self._wrapped = Settings(settings_module) File "/root/blrasp/myVirtEnv_1/lib/python3.4/site-packages/django/conf/__init__.py", line 97, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/root/blrasp/myVirtEnv_1/lib64/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>", … -
Class-based views: where to check for permissions?
I am not very comfortable using class-based views but I am aware of their perks so I am forcing myself to start using them more often. There's this view that receives a path param: manage/:id to manage a particular entity. class MyView(TemplateView): template_name = '...' def get_context_data(self, **kwargs): context = super(MyView, self).get_context_data(**kwargs) context['entity'] = get_object_or_404(Entity, pk=self.args[0]) return context An Entity includes a list of authorized users to perform special actions. This view, MyView is one of those special actions. I tried making a decorator for the view but it required finding the Entity first so I wasn't sure how to work that out. Now, I have a check_permission(request, entity) function that checks if the current user is one of these authorized ones. My question is where should I call this function in the class-based views like MyView which will be any of these views considered "special actions"? Should I call it just from get_context_data()? -
Installing a packaged Django app results in failed "migrate" error "no module named..."
Ubuntu 16.04 LTS • nginx 1.10.0 • Python 2.7.12 • Django-1.10.5 I've completed the tutorials at https://docs.djangoproject.com/en/1.10/intro/tutorial07/, which are all built using virtualenv To learn to package up my app and reuse it, I am following the tutorial at https://docs.djangoproject.com/en/1.10/intro/reusable-apps/ which does not use virtualenv, but I can't get it to work. The app is called "polls". Here is what I did to create the package: Removed all the .pyc files left in my app pip install setuptools & sudo pip install django moved my (correctly functioning) app directory from the project directory to my home directory ~$ mv -rfp example/polls django-polls in the new "django-polls" folder I created README.rst, LICENSE, and modified setup.py, by commenting out: \#'Programming Language :: Python :: 3', \#'Programming Language :: Python :: 3.4', \#'Programming Language :: Python :: 3.5', created MANIFEST.in (no documentation) built the package, with no issues: python setup.py sdist So far everything seemed to be working correctly. I want to re-use my application at a different site, but I cannot complete the migration after installing it. I install the new package with no apparent issues: pip install --user django-polls/dist/django-polls-0.1.tar.gz To finish the installation, I: add 'polls' to INSTALLED_APPS in settings.py, in … -
To long to get connection/get data from REDIS database
I have 2 servers: main server have REDIS database with Postgres backend. another is remote server. in remote server, i have tried to connect to REDIS in main server. But i am seeing that it take 3-4 seconds to query and collect data from main server. How can i reduce it or check what is the issue in my system ? Thanks, Thanh -
How do I run a script that uses django in the background
This is my code, I want to write data to my django database with a python script, because the data is generated and saved in a json file about once a day. The new data needs to be written to my django databse when the new json file is created def write_stuff(self): """Write stuff to database""" var = Match(match_id=self.match_id, match_date=self.match_date, team_a=self.team_a, team_b=self.team_b, winner=self.winner, event=self.event, closed=self.closed) var.save() When I run this code I keep on getting an error: 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. I have tried everything on SO to set DJANGO_SETTINGS_MODULE and even tried every possible path in the manage.py and wsgi.py files. What am I doing wrong? -
Geodjango using defer in manager causing keyerror on save
I have several location models that each have a MultiPolygonField called mpoly, I noticed when getting a queryset or listing in the Django admin it's really slow so I made a default manager to defer the mpoly field: class WithoutMpolyManager(models.Manager): def get_queryset(self): return super(WithoutMpolyManager, self).get_queryset().defer('mpoly') This speeds things up a lot in the admin and getting a queryset where I don't need the mpoly field, getting a single instance allows access to the mpoly field fine. The problem is when I want to save an instance in the admin or otherwise I get the error: File "/local/lib/python2.7/site-packages/django/db/models/base.py", line 692, in save isinstance(self.__class__.__dict__[f.attname], DeferredAttribute)) KeyError: 'name' name is another field that is not being deferred, is there anyway to fix this or another way to speed up querys like admin listing where mpoly is not needed? -
Django - copy and insert queryset clone using bulk_create
My goal is to create a clone of a queryset and then insert it into the database. Following the suggestions of this post, I have the following code: qs_new = copy.copy(qs) MyModel.bulk_create(qs_new) However, with this code I run into duplicate primary key error. As for now, I only can come up with the following work-around: qs_new = copy.copy(qs) for x in qs_new: x.id = None MyModel.bulk_create(qs_new) Question: Can I implement this code snippet without going through loop ? -
Don't see Django in Docker container
I want to run Django in a simple Docker container. First I built my container with Docker-file. There wasn't anything special in it (only FROM, RUN and COPY commands) Then I ran my container with command docker run -tid -p 8000:8000 --name <container_name> <image> Entered my container: docker exec -it <container_name> bash Ran Django server: python manage.py runserver Got: Starting development server at http://127.0.0.1:8000/ But when I go to 127.0.0.1:8000 I see nothing: The 127.0.0.1 page isn’t working There are no Nginx or other working servers. What am I doing wrong? -
Submitting all forms on a page with JavaScript using ajax at once to Django
I have a page with multiple forms that have a guid attached to the id. I wrote this JavaScript from an amalgamation of stack post. I'm not that great at JavaScript. When I submit my form some of my form text boxes disappear, and the data passed to django has no post values. If I log the form right before I send it serialized with ajax using console.log(formData[0]); it logs the form data and all of the elements. When i print out the post values, and return the post values to the page using django its completely blank. The submission isn't serializing the forms. I assume this is because they exist as an array of forms attached to the main generated form frmCollector. When I submit its null to django. How can I combine all forms and use an ajax submit to send as a object to django. I would be ok with it building a json object. The forms have unique uuids so I don't know what those are. I could build a list but I'm sure there is a more efficient way to do this in javascript. function submitAllDocumentForms() { var arrDocForms = document.getElementsByTagName('form'); var formCollector = document.createElement("form"); … -
Django model in combination with the admin site
I got these tables in the models file: **class ingredient (models.Model):** ingredient_row_id=models.IntegerField(primary_key=True, editable=False) ingredient_name=models.CharField(max_length=50) def __str__(self): return str(self.ingredient_name) **class receip(models.Model):** receip_row_id=models.IntegerField(primary_key=True, editable=False) receip_id=models.IntegerField() receip_name=models.CharField(max_length=50) receip_ingredient=models.ForeignKey(ingredient) receip_ingredient_quantity=models.DecimalField(max_digits=5,decimal_places=2) def __str__(self): return str(self.receip_name) **class prod(models.Model):** product_row_id=models.IntegerField(primary_key=True, editable=False) product_name=models.CharField(max_length=50) product_price=models.DecimalField(max_digits=5,decimal_places=2) product_receip=models.ForeignKey(receip) def __str__(self): return str(self.prod_name) What I want to do is to define a product which is done by a specific receip. In this receip is given the quantity of each ingredient. Now I want to combine all these. Lets say i have in ingredient a Cherry and Water. Now the receip is cherry water. So I got this in receip: Now I want to combine this in the admin Panel As you can see I can choose between two "receips" because it refers to the receip_row_id not to the receip_id. So is there any way to "combine" these to so that I only got one in the admin site. Maybe I need to change my models.py to smth else or optimize the admin.py . Somebody got an idea? Greetings -
Function and attribute in the same time
When I use @property on a function test() in Django, I have to modify test() throughout my program. Does a function could also be a attribute in Django (both in the same time)? Thanks in advance! -
How to add Redis Database in Django-1.9?
I Want to add Redis Database in Django-1.9, so i followed this documents for integration https://niwinz.github.io/django-redis/latest/ But i didn't find any clue on how to mention Database name in the settings, Here i want to mention Redis as a database on behalf Sqlite3, If uncommented this line django is throwing an Error of DATABASE not found DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'sqlite3'), } } Thanks in Advance for your solution -
Can I change Django's sessionid token length?
I would like to change the length of Django's sessioid tokens, so instead of 32 characters it would be something insane, like 64 characters. I know that's a lot, but can it be done? Are there reasons to never do something like this? I know the key length is defined in django.contrib.sessions.backends in class SessionBase, but I can't seem to find instructions how to override backend functions or replace them. Ps. I'm new to web development, so I find it difficult to understand some of the documentation. With C++ it was so much easier... -
Best way to build and integrate a complex SPA front-end with Django Rest Server?
At my company we're using Django Rest Framework on the server to build out APIs, and consuming those APIs on the front-end with a client built in React and bundled together with webpack. We're hosting the entire package on Heroku. My question is, are there any tools or packages that automate the integration with a front-end client? Specifically, one that can allow us to do a Git pull from the client repo, perform an npm build, then move the files to the correct directories? Right now it's a manual process to release updates, since our server is only configured for python and not node. So I need to perform the npm build on my machine, and then upload a new version to s3, which the Django app retrieves. It's an ugly and manual process right now, and I'd be very grateful for any suggestions on how to streamline the process. Thanks! -
TemplateDoesNotExist at /accounts/login/ error
I got a error, TemplateDoesNotExist at /accounts/login/ registration/login.html. I think I should prepare login.html file maybe.But I also have not heared Django do not have to prepare anything almost to login&logout. Next,I made login.html in accounts/templates/accounts.But this error is not disappeared. What should I do ? I wrote in urls.py of accounts, from django.conf.urls import url from django.contrib.auth.views import login, logout urlpatterns = [ url(r'^login/$', login, name='login'), url(r'^logout/$', logout, name='logout') ] in urls.py of parent app, from django.conf import settings from django.conf.urls import include, url from django.conf.urls.static import static from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^accounts/', include('accounts.urls')), url(r'^api/', include('UserToken.urls')), ] in TEMPLATES of setting.py of parent app 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', ], }, }, ]