Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Processing an uploaded file using Django
I'm attempting to process an uploaded CSV file using Django. The main logic of how I go about doing this is expressed in both the models.py and views.py scripts. Once I've uploaded the file, I'm unable to process any of the content (in my views.py). Here are the two scripts, but if there's any more information I can provide, I'd be happy to. In my models.py file, I have two classes, one for the document itself, and the other class for the fields in the file. models.py: from django.db import models import os class Document(models.Model): docfile = models.FileField(upload_to='documents') class DocumentEntry(models.Model): document = models.ForeignKey(Document, on_delete=models.CASCADE) field = models.CharField(max_length=250, default="TEST") Next, in my views.py I get the file that was uploaded via the request.FILES['docfile'] and pass it to the handle_files() function. However, when I try to loop through the reader, I'm unable to access any of the elements in the file that was uploaded. views.py: from django.shortcuts import render from django.conf import settings from django.http import HttpResponseRedirect from django.core.urlresolvers import reverse import csv from .models import Document, DocumentEntry from .forms import UploadFileForm def process_file(request): # Handle file upload if request.method == 'POST': form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): handle_files(request.FILES['docfile']) # Redirect to … -
trying to config SSL apache2 but always shows apache start page
I am trying to setup SSL on my apache2 running django app. I tried to change my config files based comnets here. But my django app page doesn't show anymore and instead always apache start page is served. None of the underlying urls of the site are accessible. I am very clueless at this point. Thank you for you help in advance. 000-default <VirtualHost *:80> ServerName example.com ServerAdmin admin@example.com ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined # This is optional, in case you want to redirect people # from http to https automatically. RewriteEngine On RewriteCond %{SERVER_PORT} !^443$ RewriteRule ^(.*)$ https://%{HTTP_HOST}$1 [R=301,L] </VirtualHost> default-ssl <VirtualHost *:443> ServerName example.com ServerAdmin admin@example.com # Django Application Alias /static /var/www/CordeliaHanelFrontend-master/www/dist <Directory /var/www/CordeliaHanelFrontend-master/www/dist> Require all granted </Directory> <Directory /var/www/CordeliaHanelBackend-master/CordeliaHanelBackend> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess myapp python-path=/var/www/CordeliaHanelBackend-master/:/var/www/CordeliaHanelBackend-master/env/lib/python2.7/site-packages WSGIProcessGroup myapp WSGIScriptAlias / /var/www/CordeliaHanelBackend-master/CordeliaHanelBackend/wsgi.py SSLEngine on SSLCertificateFile /etc/apache2/ssl/apache.crt SSLCertificateKeyFile /etc/apache2/ssl/apache.key </VirtualHost> -
Celery Error: no module name [django app name] - Have checked the if the celery file is correct but still get issue?
When I Run celery -A uno worker -l info in the terminal I get the error File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) ImportError: No module named uno Here is my celery.py which is in the uno app where the django settings.py file is. from __future__ import absolute_import import os from celery import Celery from django.conf import settings os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'uno.settings') app = Celery('uno') # This reads, e.g., CELERY_ACCEPT_CONTENT = ['json'] from settings.py: app.config_from_object('django.conf:settings') # For autodiscover_tasks to work, you must define your tasks in a file called 'tasks.py'. app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) @app.task(bind=True) def debug_task(self): print("Request: {0!r}".format(self.request)) I am using Ubuntu but experience the same error on a Mac. I install celery via pip in a virtualenv I am not sure what is wrong or what I am missing here. Thank you very much. -
Django: failed to overwrite handler404
Part urls.py (for testing): old_handler404 = handler404 def custom_page_not_found(request): from django.http import HttpResponseNotFound if request.path.startswith('/myapp/api'): try: return HttpResponseNotFound( json.dumps( {'info': 'page not found'} ), content_type='application/json') except Exception as e: print 'Exception:', e #return HttpResponseNotFound('Page Not found', content_type='text/html; charset=utf-8') try: res = old_handler404( request ) except Exceptino as e: print 'Exception:', e return res handler404 = custom_page_not_found For /myapp/api, it works fine. but for other cases, it returned 500 instead of expected 404. Any comments welcomed. Thanks -
settings.database is improperly configured when using Amazon RDS postgres database
I am using Django and when i load this code it works when signing into the admin login. However when proceeding after logging in it comes up with the database being improperly configured. I have added a else statement and have tried using a local database with it. But it comes up with a 500 http error when i have connected it. Thanks for the help! if 'database' in os.environ: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': os.environ['data'], 'USER': os.environ['data'], 'PASSWORD': os.environ['data'], 'HOST': os.environ['xxxxxxxxxxxxxxxxxxxxxxxxxxx'], 'PORT': os.environ['xxxx'], } } I am also using mac(osx) -
Form stopped saving to database after TextField was changed to HTMLField
I had a working input form for my model, which included a TextField called 'Opis'. The instances of the model were successfully saved to the database. However, I wanted to give my users more options when writing -- and storing -- that particular bit of text. So I installed TinyMCE, changed the TextField to HTMLField and discovered that this, together with putting <head> {{ form.media }} </head> at the beginning of my template was enough for the input field to be rendered as a TinyMCE widget. That is, I kept my old ModelForm, and what it displayed changed, which I thought was nice and convenient. However, when the user submits the form, nothing happens -- it seems the form is valid, but the database is not updated. In my models.py: from tinymce.models import HTMLField class Kurs(models.Model): [skipping...] opis = HTMLField() [skipping the rest] in my forms.py: class KursForm(ModelForm): class Meta: model = Kurs fields = "__all__" in my views.py: def createcourse(request): if request.method=='POST': form = KursForm(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect('/polls/usersite') else: form = KursForm() return render(request, 'polls/createcourse.html', {"form" : form}) and in the createcourse.html: <head>{{ form.media }}</head> <form action="" method="post"> {% csrf_token %} {{ form }} <input type="submit" value="Submit" … -
ISSUES Defining Cron jobs in Procfile (Heroku) using apscheduler for Django project
Hi stackoverflow community, I am having a problem scheduling a cron job which requires scraping a website and storing it as part of the model (MOVIE) in the database. The problem is that the model seems to get loaded before Procfile is executed. How should I create a cron job which runs internally in the background and storing scraped information into the database? Here are my codes: Procfile: web: python manage.py runserver 0.0.0.0:$PORT scheduler: python cinemas/scheduler.py scheduler.py: # More code above from cinemas.models import Movie from apscheduler.schedulers.blocking import BlockingScheduler sched = BlockingScheduler() @sched.scheduled_job('cron', day_of_week='mon-fri', hour=0, minutes=26) def get_movies_playing_now(): global url_movies_playing_now Movie.objects.all().delete() while(url_movies_playing_now): title = [] description = [] #Create BeatifulSoup Object with url link s = requests.get(url_movies_playing_now, headers=headers) soup = bs4.BeautifulSoup(s.text, "html.parser") movies = soup.find_all('ul', class_='w462')[0] #Find Movie's title for movie_title in movies.find_all('h3'): title.append(movie_title.text) #Find Movie's description for movie_description in soup.find_all('ul', class_='w462')[0].find_all('p'): description.append(movie_description.text.replace(" [More]",".")) for t, d in zip(title, description): m = Movie(movie_title=t, movie_description=d) m.save() #Go to the next page to find more movies paging = soup.find( class_='pagenating').find_all('a', class_=lambda x: x != "inactive") href = "" for p in paging: if "next" in p.text.lower(): href = p['href'] url_movies_playing_now = href sched.start() # More code below from django.db import models cinemas/models.py: … -
Django- jQuery and tags?
I'm using an app that stores/manages forms. I've been wanting to list all the forms in a page, and if the user clicks on a form name, then that form is fetched (via jQuery?) and presented in that same page, beneath the form list, so that the user can fill it and submit! The person who made this app left a template to get the html for a specific form, as for example {% render_built_form slug=form_instance.slug %} I'm very confused about the correct way to go at this. Is it possible/correct to use a scheme like: (The list of forms is presented, using some Javascript to make a Button for each of them) When a user clicks on a button, the corresponding form (html string) is fetched, somehow using the tag (with the form's slug in there) 'inside' jQuery The html form is displayed beneath the list and the user can now fill it. Is this a correct/feasible idea, or am I confusing these concepts? If so, pointers on how to use jQuery with a tag would be super helpful. -
Python/ Django- copying buttons from one HTML page to another
I have just taken over the development of some project management software that has been written in Python/ Django- having not used Python or Django much at all before... There are a few buttons displayed on one of the webpages that it would be useful to display on another page within the application. I can see that these buttons are defined in budget.html with the following code: {% block page_options %} <a class="button m-r-md" href="{% url 'costing:export_csv' budget.id %}">Export to Excel</a> <a class="button m-r-md" href="{% url 'costing:schedule_of_works_post_dep' budget.id %}" target="_blank">Schedule of works</a> <a class="button m-r-md" href="?pdf=1" target="_blank">PDF</a> <input data-view-url="{% url 'costing:combined_budget' project.id %}?search=" type="text" id="item_search" placeholder="Item search" /> {% endblock page_options %} The other page, where I want to be able to use them- variations.html has the following code already in its {%block page_options %} block: {% block page_options %} <button class="button modalBtn" name="variation">+ Add variation</button> <a class="button" href="{% url 'costing:add_omit_builder' project.id %}">+ Add group</a> <a class="button" id="scas" data-view-url="{% url 'costing:preview_scas' project.budget_overview.version.id %}" href="{% url 'costing:scas_2_variations' project.budget_overview.version.id %}">+ Standard cost assumptions</a> <!--ERF(17/11/2016 @ 1700) Add buttons to export adds/ omits table to excel --> {% endblock page_options %} So I tried copying and pasting the code from the first page … -
Nginx Server Is Not Playing Media Files in Safari
I found that direct url to a resource like wav is is not playing in the safari browser while the same url works fine in other browsers. I Tried checked /etc/nginx/mime.types and added "audio/wav wav". response headers are having content-type : audio/x-wav so I don't think there is any problem with the mime-type I served the same resource with apache server and without any issue it works fine in safari, when i'm inspecting and comparing the response headers I see that only important header missing is the 'Accept-Ranges:bytes' but I believe that should not be a problem when the files are directly served to the browser Reply would be greatly appcriated because I was working this matter hours now. This is the apache result This is the nginx result -
Send email from gmail with Django and Python
I found a lot of posts regarding send email with django, but I've a specific problem with gmail: error image here are my settings: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = "smtp.gmail.com" EMAIL_HOST_USER = "myemail@gmail.com" DEFAULT_FROM_EMAIL = EMAIL_HOST_USER EMAIL_HOST_PASSWORD = 'mypassword EMAIL_PORT = 587 EMAIL_USE_TLS = True and my view is: from django.core.mail import EmailMessage, send_mail if request.method == 'POST': name = request.POST.get('name','') email = request.POST.get('email','') subject = request.POST.get('subject','') text = request.POST.get('text','') message = 'From: ' + email + '\n\n\n' + text send_mail(subject, message, 'myemail@gmail.com', ['myemail@gmail.com'], fail_silently=False) Can you please tell me why I get this error? I also checked for google settings like "access from less secure applications" and similar thank you in advance!!! -
Reloading the same page with slightly different content on different condition
i have a django app where i have to load a same page twice with slightly different content. I have a login page and i am force logging out user if they login from different machine. They will be logged out and redirected to login page but this time the login page should have extra message like " you have been logged out because ...". I have a javascript that listen and checks for the duplicate login and then redirect them to login page. PS - i can't put my code as its not allowed to make public. -
Why is virtualenvwrapper not adding my environment location to my $PATH
I am trying to create a django project, using virtualenvwrapper to isolate/sandbox different projects. Here are the commands I typed so far ... memyself@somebox:~/path/to/foo_project$ mkvirtualenv foo Using base prefix '/usr' New python executable in /home/memyself/.virtualenvs/foo/bin/python3 Also creating executable in /home/memyself/.virtualenvs/foo/bin/python Installing setuptools, pip, wheel...done. virtualenvwrapper.user_scripts creating /home/memyself/.virtualenvs/foo/bin/predeactivate virtualenvwrapper.user_scripts creating /home/memyself/.virtualenvs/foo/bin/postdeactivate virtualenvwrapper.user_scripts creating /home/memyself/.virtualenvs/foo/bin/preactivate virtualenvwrapper.user_scripts creating /home/memyself/.virtualenvs/foo/bin/postactivate virtualenvwrapper.user_scripts creating /home/memyself/.virtualenvs/foo/bin/get_env_details I then installed django in the foo env: (foo) memyself@somebox:~/path/to/foo_project$ pip install django Collecting django Using cached Django-1.10.3-py2.py3-none-any.whl Installing collected packages: django Successfully installed django-1.10.3 I then proceed to attempt to create a django website by entering the following commands: (foo) memyself@somebox:~/path/to/foo_project.foo$ python django-admin.py startproject mysite python: can't open file 'django-admin.py': [Errno 2] No such file or directory (foo) memyself@somebox:~/path/to/foo_project.foo$ Not believing what I was seeing, I decide to run a few checks, to make sure I'm not going mad ... (foo) memyself@somebox:~/path/to/foo_project.foo$ pip list --format=legacy Django (1.10.3) pip (9.0.1) setuptools (28.8.0) wheel (0.29.0) (foo) memyself@somebox:~/path/to/foo_project.foo$ pip show django Name: Django Version: 1.10.3 Summary: A high-level Python Web framework that encourages rapid development and clean, pragmatic design. Home-page: http://www.djangoproject.com/ Author: Django Software Foundation Author-email: foundation@djangoproject.com License: BSD Location: /home/memyself/.virtualenvs/foo/lib/python3.5/site-packages Requires: (foo) memyself@somebox:~/path/to/foo_project.foo$ which django-admin.py /home/memyself/.virtualenvs/foo/bin/django-admin.py I'm using a simple heuristic that … -
django-autocomplete-light using SQL Alchemy instead of Django ORM
I would like to use django-autocomplete-light to autocomplete some fields from an external database that cannot be adjusted to conform to the DjangoORM requirements. Therefore I use SQL Alchemy to connect to this db. I cannot find out how to do this. As an example I would like to make the autocomplete use the following instead of the Django Model for the table (Which doesn't work because there is a dual column primary key and no id field. query = (session.query(TableA.FIRSTNAME).distinct(TableA.FIRSTNAME) .filter(TableA.FIRSTNAME.match(name))) data = query.limit(100).all() Effectively I would like to make the field autocomplete the names from my above query. Instead of using the Django qs as shown in the documentation: class CountryAutocomplete(autocomplete.Select2QuerySetView): def get_queryset(self): # Don't forget to filter out results depending on the visitor ! if not self.request.user.is_authenticated(): return Country.objects.none() qs = Country.objects.all() if self.q: qs = qs.filter(name__istartswith=self.q) return qs class PersonForm(forms.ModelForm): birth_country = forms.ModelChoiceField( queryset=Country.objects.all(), widget=autocomplete.ModelSelect2(url='country-autocomplete') ) -
Executing an external python script from django, leads to segmentation fault
I wrote a script a while ago, which creates some figures and does a few SQL querys with psycopg2 on postgresql after processing a file "A". This script works fine when executed on its own. Tested multiple times. At the moment I am working on a django project, where you can upload this file "A". My Idea is to use the script I made on that file, to create the output, which will then be displayed on the webside. I had no problem to implement the file uploading process, than I copyed the file into a subfolder from the script using shutil. But when I try to run the script to process the file from withhin the django script, I get a segmentation fault error. Again: python script #runs perfectly well In django app/views.py from script import function function() #segmentation fault I know, that django in debug modus keeps track of sql querys and excessive memory use can then lead to a segmentation fault. Source: turn off SQL logging while keeping settings.DEBUG? As I am perfoming sql querys inside the script I guess the reason it crashes could be this debug behaviour. So I was wondering if there is a … -
django-rest-framework non orm-based filtering
I am using DjangoRestApi and while it works like a charm with queryset (orm-based) views, I am struggling to make views that use different back-end to behave same way orm-based views are responding. Notably I wanted to add filters that are validated and parsed automatically. Pseudo code below: class NewsFilter(django_filters.FilterSet): category = django_filters.NumberFilter(name='category') limit = django_filters.NumberFilter(name='limit') page = django_filters.NumberFilter(name='page') class NewsView(generics.APIView): filter_class = NewsFilter def get(self, request): filters = self.filter_class(request.GET) # not sure, what to put here payload = logic.get_business_news(**filters.data) # same return Response(payload, status=status.HTTP_200_OK) Any hint how to tackle problem will be apprecaited. Ultimate goal is to: not manually type and parse each variable have filter controls on /api/ backend rendered same way One could think, job that is done in typical Django by form that validate and cast variables to appropriate format. -
Python Django manage.py exception
I'm currently working my way through a course on Lynda for learning Django. I set up just a basic project using django-admin startproject project_name After that, I tried running the python manage.py script to see a list of available commands. This is what I got back: $ python manage.py Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "C:\Python27\lib\site-packages\django\core\management\__init__.py", line 367, in execute_from_command_line utility.execute() File "C:\Python27\lib\site-packages\django\core\management\__init__.py", line 341, in execute django.setup() File "C:\Python27\lib\site-packages\django\__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Python27\lib\site-packages\django\apps\registry.py", line 108, in populate app_config.import_models(all_models) File "C:\Python27\lib\site-packages\django\apps\config.py", line 199, in import_models self.models_module = import_module(models_module_name) File "C:\Python27\lib\importlib\__init__.py", line 37, in import_module __import__(name) File "C:\Python27\lib\site-packages\django\contrib\auth\models.py", line 300, in <module> class AbstractUser(AbstractBaseUser, PermissionsMixin): File "C:\Python27\lib\site-packages\django\db\models\base.py", line 274, in __new__ new_class.add_to_class(field.name, new_field) File "C:\Python27\lib\site-packages\django\db\models\base.py", line 316, in add_to_class value.contribute_to_class(cls, name) File "C:\Python27\lib\site-packages\django\db\models\fields\__init__.py", line 694, in contribute_to_class cls._meta.add_field(self) File "C:\Python27\lib\site-packages\django\db\models\options.py", line 277, in add_field self.local_fields.insert(bisect(self.local_fields, field), field) File "C:\Python27\lib\functools.py", line 56, in <lambda> '__lt__': [('__gt__', lambda self, other: other < self), File "C:\Python27\lib\functools.py", line 56, in <lambda> '__lt__': [('__gt__', lambda self, other: other < self), File "C:\Python27\lib\functools.py", line 56, in <lambda> '__lt__': [('__gt__', lambda self, other: other < self), File "C:\Python27\lib\functools.py", line 56, in <lambda> '__lt__': [('__gt__', lambda self, other: other … -
Python Social Auth - Redirect to a URL after raising an AuthException
When the user try to login in my website using his google account I check if his gmail already is registered in the DB. This is my pipeline.py def check_email(request, backend, details, uid, user=None, *args, **kwargs): if backend.name == 'google-oauth2': # verifica se é um usuário jah existente pelo google, e que apenas vai fazer o login if uid and user: pass # se ele não existe é pq será registrado else: # pega o e-mail do cara que vai ser registado email = details.get('email', '') # procura na db se existe algum email parecido, se existir volta pro login count = User.objects.filter(email=email).count() if count>0: raise AuthException(backend, 'Not unique email address.') The error is raised at the browse: Exception Raised So, I am wondering how I could redirect to the login page again with the message. I tryed to use an HttpRedirect, it works fine, but it is not possible do use django message framework during pipeline process. Thanks -
How do we define @list_route that accept arguments
In my application i have this ModelViewSet with one @list_route() defined function for getting list but with different serializer. class AnimalViewSet(viewsets.ModelViewSet): """ This viewset automatically provides `list`, `create`, `retrieve`, `update` and `destroy` actions. """ queryset = Animal.objects.all() serializer_class = AnimalSerializer // Default modelviewset serializer lookup_field = 'this_id' @list_route() def listview(self, request): query_set = Animal.objects.all() serializer = AnimalListingSerializer(query_set, many=True) // Serializer with different field included. return Response(serializer.data) The Default AnimalViewSet with this /api/animal/ end point yield this serialized data result as based on AnimalSerializer definition. { "this_id": "1001", "name": "Animal Testing 1", "species_type": "Cow", "breed": "Brahman", ... "herd": 1 }, { "this_id": "1004", "name": "Animal Testing 2", "species_type": "Cow", "breed": "Holstien", .... "herd": 1 }, { "this_id": "1020", "name": "Animal Testing 20", "species_type": "Cow", "breed": "Brahman", .... "herd": 4 }, And the other one which is a @list_route() defined function named listview may have this end point /api/animal/listview/ which yields this result as defined in AnimalListingSerializer structure. { "this_id": "1001", "name": "Animal Testing 1", "species_type": "Cow", "breed": "Brahman", .... "herd": { "id": 1, "name": "High Production", "description": null } }, { "this_id": "1004", "name": "Animal Testing 2", "species_type": "Cow", "breed": "Holstien", .... "herd": { "id": 1, "name": "High Production", "description": null … -
Connect mysql to django
I would to connect Django (1.10) from my localhost (MacOS X) to a Mysql Database (Mysql-server) which is located on a distant server (Ubuntu 14.04) instead of sqlLite3. I made some changes in the Django' settings.py file : DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'Etat_Civil', 'USER': 'root', 'PASSWORD': '*****', 'HOST': '172.**.**.58', 'PORT': '80', } On the distant server, I installed mysql-server and I juste created a table. And when I run : python manage.py migrate I get this error : MacBook-Pro-de-Valentin:Etat_Civil valentinjungbluth$ python manage.py migrate Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/Library/Python/2.7/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line utility.execute() File "/Library/Python/2.7/site-packages/django/core/management/__init__.py", line 341, in execute django.setup() File "/Library/Python/2.7/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/Library/Python/2.7/site-packages/django/apps/registry.py", line 108, in populate app_config.import_models(all_models) File "/Library/Python/2.7/site-packages/django/apps/config.py", line 199, in import_models self.models_module = import_module(models_module_name) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/Library/Python/2.7/site-packages/django/contrib/auth/models.py", line 4, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "/Library/Python/2.7/site-packages/django/contrib/auth/base_user.py", line 52, in <module> class AbstractBaseUser(models.Model): File "/Library/Python/2.7/site-packages/django/db/models/base.py", line 119, in __new__ new_class.add_to_class('_meta', Options(meta, app_label)) File "/Library/Python/2.7/site-packages/django/db/models/base.py", line 316, in add_to_class value.contribute_to_class(cls, name) File "/Library/Python/2.7/site-packages/django/db/models/options.py", line 214, in contribute_to_class self.db_table = truncate_name(self.db_table, connection.ops.max_name_length()) File "/Library/Python/2.7/site-packages/django/db/__init__.py", line 33, in __getattr__ return getattr(connections[DEFAULT_DB_ALIAS], item) File "/Library/Python/2.7/site-packages/django/db/utils.py", … -
Is there a security risk to serve Django admin page on regular http rather than Https?
Dear Expert Fellows, I just finished my first experience with Django on real application and we are running it on apache2. Since I am newbie I am wondering if it is right to have admin page served on http? Is https a better solution??? how much of risk will I be experiencing by not having it run on https? Thank you very much for your valuable comments. Cheers, -
Django - Filtering Fields when Creating Model Admin View
Say I have the following scenario: class ModelA(models.Model): def __str__(self): return self.name name = models.Charfield(max_length=255) class ModelB(models.Model): def __str__(self): return self.my_name a_name = models.ForeignKey(ModelA) my_name = models.Charfield(max_length=255) next_b_model = models.ForeignKey('self', related_name='next', blank=True, null=True) I'd like to create all the models in the admin view. Say I create a ModelA with the name of 'Puppies' and go to create a ModelB with an a_name that refers to 'Puppies'. Is there a way to filter the dropdown for next_b_model to only list the created ModelBs that also have a_name referencing 'Puppies'? I'm relatively new to Django so please be merciful. -
Globally available object in django for frequent acess
I'm relatively new to Django & learning it bit-by-bit. I've subscribed to a service, which uses a DLL to provide the data I need. To get the required data from the service, I have to make a few initializations; the code for which takes around 2-3 seconds (Requires dispatching a DLL, and then making an init call as follows:) from win32com.client import Dispatch #pythoncom.CoInitialize() zk = Dispatch("easyconnect.serverside") print(zk.cmdInit("id", "pass", "ip")) I need the zk object be available globally, to all the other modules so that I do not have to perform init ambiguously and speed up the data access process. I tried Django's caching framework, which helps caching the entire site, or web pages, but I think it's not what I want. Also, putting zk into the cache returns me an error which states that it cannot be put into the cache. What are some alternatives to address my problem? -
Django: correct way to specify model (list of tuples)
I'm not happy with my current model and wanted to ask if there is a better/preferred way to achieve the same result. What to I want? An object A that contains a number of lists. Each list contains tuples, the first entry being a date object, the second one is either a float or an integer. If I delete A, B should also be deleted. If I delete B I want to just have an empty list. How I tried to accomplish it: class TimeValueIntSequence(models.Model): pass class TimeValueFloatSequence(models.Model): pass class TimeValueInt(models.Model): time = models.DateField() value = models.IntegerField() sequence = models.ForeignKey(TimeValueIntSequence, models.CASCADE, blank=False, null=False) class TimeValueFloat(models.Model): time = models.DateField() value = models.FloatField() sequence = models.ForeignKey(TimeValueFloatSequence, models.CASCADE, blank=False, null=False) class A(models.Model): field1 = models.OneToOneField(TimeValueIntSequence, models.SET_NULL, blank=True, null=True, related_name='field1') field2 = models.OneToOneField(TimeValueIntSequence, models.SET_NULL, blank=True, null=True, related_name='field2') field3 = models.OneToOneField(TimeValueFloatSequence, models.SET_NULL, blank=True, null=True, related_name='field3') What is wrong? Not elegant (efficient?) If I delete an object of type A the sequences do not get deleted. Do you have any feedback? Thank you! -
Simple RDF mysql backend
Okay so I have a more abstract mysql kind of question and I'm not sure where to begin as their are not a lot of resources online in this area. WARNING I do not have a lot of experience with mysql. Okay, so what I have built so far is a simple django interface that I have incorporated a cTAKES NLP pipeline into. This pipeline runs when the user submits a a block of text associated with a study name and spits out an array of triples automatically generated using the Semantic Role Labeler and Dependency Parser. [(Weight_Gain, mayLeadTo, obesity), (Cancer, mayBe, present), (Study, observedChangeIn, sleep_patterns), ....] What I would like to do with this is store the individual triples in the simplest mysql schema possible where the primary key is the study name and each row contains a subject, object and predicate field corresponding to the triple structure. So far I am just saving the output as a direct chunk of the triple_store: Code for handling the script and storing the data: if form.is_valid(): instance = form.save(commit=False) instanceValuesList = [instance.Study_Abstract,instance.Study_Methods,instance.Study_Results] instanceValuesString = u" ".join(instanceValuesList).encode('utf-8').strip() tempFileINLocation ='/tmp/'+randomword(8)+'.txt' tempFileIN = open(tempFileINLocation, 'w') tempFileIN.write(instanceValuesString) tempFileIN.close() tempFileOUTLocation ='/tmp/'+randomword(8)+'.txt' argList=[tempFileINLocation, tempFileOUTLocation] p = subprocess.Popen(['/Users/joshuavaldez/Desktop/ProvCaRe-test2/ProvCaRe/static/scripts/CtakesClinicalPipeline/run_pipeline.sh'] …