Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django 1.10 :: creating both instances on a one-to-one relationship at the same time
I am working with a Django model which has a one-to-one relationship, and I wonder if I am doing this the best possible way. To give you some context, this are the involved classes with their cardinal relationships. Affiliate (1)----(1) Account class Affiliate(models.Model): uid = models.CharField(_('Uid'), max_length=128, blank=True, null=True) [...] class Account(models.Model): affiliate = models.OneToOneField(Affiliate, on_delete=models.CASCADE) # Here it goes. [...] I did consider joining both Affiliate and Account in the same object, but that just does not seem right. They are different model entities. I actually use them always separately, except just in one place. When I create an affiliate for any given Organization, that Affiliate must have an account created with it. So... what I would like to ask is: Is there a better way of creating both entities at the same time, other tan creating both and relating them? This is the code in my view (post for the AffiliateModelForm) form = AffiliateForm(request.POST) if form.is_valid(): affiliate = form.save() account = Account() account.affiliate = affiliate account.save() Edit: Should I override the form.save() method? Is that it? Edit 2: Forgot to clarify. AffiliateForm has the full Affiliate model's fields and it is used for editing the Affiliate as well, … -
Google Streaming Speech Recognition on an Audio Stream Python
I have searched through all the available docs of Google but I could not find an example of streaming speech recognition on an audio stream in Python. Currently, I am using Speech Recognition for Python in Django to get the audio from the user and then listen to the audio. I can then save the file and run the google speech recognition or directly from the instance of the audio created. Can somebody guide me how to perform streaming speech recognition on an audio stream ? -
django fails to import wsgi after restructuring?
My initial project structure is like this: manage.py foo/ wsgi.py settings.py urls.py manage.py #!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "foo.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv) New structure: manage.py src/ foo/ wsgi.py settings.py urls.py manage.py #!/usr/bin/env python import os import sys project_root = os.path.dirname(os.path.abspath(__file__)) print project_root if __name__ == "__main__": sys.path.insert(0, os.path.join(project_root, 'src')) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "foo.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv) Then during the deployment, I have this error of ImportError: No module named foo.wsgi: $ gunicorn foo.wsgi:application 2017-05-20 16:53:31 [19107] [INFO] Starting gunicorn 18.0 2017-05-20 16:53:31 [19107] [INFO] Listening at: http://127.0.0.1:8000 (19107) 2017-05-20 16:53:31 [19107] [INFO] Using worker: sync 2017-05-20 16:53:31 [19111] [INFO] Booting worker with pid: 19111 2017-05-20 16:53:31 [19111] [ERROR] Exception in worker process: Traceback (most recent call last): File "/var/www/html/django-project/foo/env/local/lib/python2.7/site-packages/gunicorn/arbiter.py", line 495, in spawn_worker worker.init_process() File "/var/www/html/django-project/foo/env/local/lib/python2.7/site-packages/gunicorn/workers/base.py", line 106, in init_process self.wsgi = self.app.wsgi() File "/var/www/html/django-project/foo/env/local/lib/python2.7/site-packages/gunicorn/app/base.py", line 114, in wsgi self.callable = self.load() File "/var/www/html/django-project/foo/env/local/lib/python2.7/site-packages/gunicorn/app/wsgiapp.py", line 62, in load return self.load_wsgiapp() File "/var/www/html/django-project/foo/env/local/lib/python2.7/site-packages/gunicorn/app/wsgiapp.py", line 49, in load_wsgiapp return util.import_app(self.app_uri) File "/var/www/html/django-project/foo/env/local/lib/python2.7/site-packages/gunicorn/util.py", line 354, in import_app __import__(module) ImportError: No module named foo.wsgi Traceback (most recent call last): File "/var/www/html/django-project/foo/env/local/lib/python2.7/site-packages/gunicorn/arbiter.py", line 495, in spawn_worker worker.init_process() File "/var/www/html/django-project/foo/env/local/lib/python2.7/site-packages/gunicorn/workers/base.py", line 106, in init_process self.wsgi = self.app.wsgi() File … -
Django queryset annotation, charfield with choices and trying to get the display value
The relevant bits of my model: class AnalyticRecord(models.Model): APP = "APP" WEB = "WEB" DASH = "DASH" SOURCE_CHOICES = ( (APP, "Mobile Application"), (WEB, "Website"), (DASH, "User Dashboard")) user = models.ForeignKey(User, blank=True, null=True) event = models.ForeignKey(Event) source = models.CharField(max_length=25, choices=SOURCE_CHOICES) I am trying to run an aggregation command. It works just fine like this: data = event.analyticrecord_set.all().values("source").\ annotate(label=Concat("source", Value(None), output_field=CharField())) However, the problem is the annotation label returns "APP", "WEB", "DASH" instead of the actual display value. I know I can use get_FOO_display() normally, but how can I pull in the display value into my annotation call? I am looking to get the display values of my source field. Thanks! -
django python: missing 1 required positional argument
I am trying to define a function that has 4 arguments but I am facing a problem with my forth argument and I am pretty sure it is something stupid. Here is my code: views.py: def create_recording(request, slug, inspection_id, component_id): inspection = get_object_or_404(Inspection, pk=inspection_id) plant = get_object_or_404(Plant, slug=slug) component=get_object_or_404(Component, pk=component_id) if request.method == "POST": form = RecordingForm(request.POST) if form.is_valid(): recording = form.save(commit=False) recording.plant = plant recording.inspection=inspection recording.component=component recording.save() return redirect('data:inspection_detail', slug=plant.slug, inspection_id=inspection.id) else: form = RecordingForm() context = {'form': form, 'plant':plant,'inspection':inspection} template = 'data/create_recording.html' return render(request, template, context) here is my html file: <a href="{% url 'data:create_recording' slug=plant.slug inspection_id=inspection.id inspection_id=inspection.id component_id=2 %}"> <button type="button" class="btn btn-success"> <span class="glyphicon glyphicon-plus"></span> Chaiir </button> </a> <a href="{% url 'data:create_recording' slug=plant.slug inspection_id=2 %}"> <button type="button" class="btn btn-success"> <span class="glyphicon glyphicon-plus"></span> Table </button> </a> and I get the following error: Exception Type: TypeError Exception Value:create_recording() missing 1 required positional argument: 'component_id' -
Django API showing big time latency while retrieving data
I am currently working on Angular2 and Django (python framework). i have created a simple API in django which shows me all record from database. here is link of that API. [https://djangoshopnroar.herokuapp.com/mobile/viewAll][1] But when i call it from Angular 2. it gives me a time latency. worst thing i have only 10 records in my db. and it take almost 6-8 sec for that. i am using PostgreSQL database. Can anyone have idea why angular 2 is showing latency in time. or any suggestions how can i improve it? i will be very thankful for that. -
Edit form field value on template
I'm trying to edit the value of a form field inside a django template. I've tried a lot of stuff. I think the following is supposed to work: {% with form.name.value="asdsad" %} {{form.name}} {% endwith %} But it presents the following error: u'with' expected at least one variable assignment Nothing seems to work. What is the correct form of doing this? -
Post-installation virtualenv error
I want to deploy my django app on heroku, but when i install heroku by this command: sudo apt-get install heroku But i get some errors dpkg: ошибка при обработке пакета python-virtualenv (--configure): подпроцесс установлен сценарий post-installation возвратил код ошибки 1 При обработке следующих пакетов произошли ошибки: python-virtualenv E: Sub-process /usr/bin/dpkg returned an error code (1) virtualenv is installed but reinstall this package return the same error -
What is 'dashboard' word after {{block.super}} in django admin template
{% block extrastyle %}{{ block.super }}{% endblock %} {% block bodyclass %}{{ block.super }} dashboard{% endblock %} what is that 'dashboard' word between block's ' what does it do ? i tried removing it and and the result's were ' it caused the table's in admin template messed up. -
allow unauthenticated users to suggest changes, but wait for administrator approval before changing object
Assume I have a very simple model: class School(models.Model): name = models.CharField(max_length = 100, unique=True) I want to allow unauthenticated users to use a modelform to suggest changes to School objects, but I want to flag those changes as not yet being seen by an administrator. Once an administrator approves, I will then make the suggested change to the existing School object. What is the best way to do this? Do I need to subclass the School class, perhaps calling it UpdateToSchool and allowing users make suggestions on this subclassed model rather than the target model itself? -
Creating hierarchical urls in Django
I'm dabbling in django for the first time and I'm stuck on one single issue and it's driving me crazy. I'm trying to create a set of pages with a hierarchical url like this www.example.com/{state}/{county}. Basically the problem I'm having is that I can get www.example.com/{state}, but I don't know how to use the url system in django to carry the state over to the state/county page. What I end up getting is www.example.com//{county} urls.py app_name = 'main' urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^(?P<pk>[A-Z]{2})/$', views.StateView.as_view(), name='state'), url(r'/(?P<pk>[a-zA-Z]*)/$', views.CountyView.as_view(), name='county'), ] views.py def index(request): return render(request, 'main/index.html', {}) class StateView(generic.ListView): template_name = 'main/state.html' context_object_name = 'county_list' def get_queryset(self): counties = [ // list of a couple counties for testing purposes] return counties class CountyView(generic.ListView): template_name = 'main/county.html' context_object_name = 'water_list' def get_queryset(self): return WaWestern.objects.filter(water_name__contains='Orange') // hard coded for easy testing def redirect(request): obj = "WA" return HttpResponseRedirect(reverse('county', args=(obj,))) index.html this file is large so I'll just show an example of one of my state links <a id="s06" href="CA"> state.html {% if county_list %} <ul> {% for county in county_list %} <li><a href="{% url 'main:county' county %}">{{ county }}</a></li> {% endfor %} </ul> {% else %} <p>No counties were found.</p> {% … -
Unable to migrate Django db when using docker container
On my Windows 10 machine, I am developing a database manager. Because the backend uses LDAP and the required development libraries are only available for Linux, I want to use Docker to set up an environment with the appropriate libs. I managed to write a Dockerfile and compose file, that launch the (currently very basic) Django app in a Docker container with all the libs necessary. I would like to play around with the django-ldapdb package and for that I want to apply the migrations. When I open PyCharm's terminal and try to execute python manage.py migrate, I get an error telling me that the module ldapdb is not found. I suspect this is because the command does not use the remote Docker interpreter I set up with PyCharm. The other thing I tried is using PyCharm's dedicated manage.py console. This does not initialize properly. It says the working directory is invalid and needs to be an absolute path, although the path it shows it the absolute path to the project. I have to admit that I have no idea how this remote interpreter works and I don't see any Docker container running, so I might have not understood something … -
Django - Multiprocess Queue Not Updating
I am trying to update two values of a queue at the same time, but my code ends up in an infinite loop. I'm running it on Django View, the code below runs well but when I try it on Django it just keeps waiting. What could be happening? import multiprocessing from multiprocessing import Process ret = {'algo' : 'hola', 'beto' : 'oka'} def algo(queue): ret = queue.get() ret['algo'] = False #This is actually an API call value queue.put(ret) def beta(queue): ret = queue.get() ret['beto'] = True #This is actually an API call value queue.put(ret) queue = multiprocessing.Queue() queue.put(ret) p1 = Process(target=algo, args=(queue,)) p2 = Process(target=beta, args=(queue,)) p1.start() p2.start() p1.join() p2.join() q = queue.get() Code in Django Views.py ret = {'algo' : 'hola', 'beto' : 'oka'} def algo(queue): ret = queue.get() ret['algo'] = False #This is actually an API call value queue.put(ret) def beta(queue): ret = queue.get() ret['beto'] = True #This is actually an API call value queue.put(ret) def audio(request): if request.method == 'POST': AUDIO_FILE = path.join(os.getcwd(), "audio.wav") # use the audio file as the audio source r = sr.Recognizer() with sr.AudioFile(AUDIO_FILE) as source: audio = r.record(source) queue = multiprocessing.Queue() queue.put(ret) p1 = Process(target=algo, args=(queue,)) p2 = Process(target=beta, args=(queue,)) p1.start() … -
RelatedObjectDoesNotExist Exception
enter image description here I tried to define prefix of signing in user, but I got this exception RelatedObjectDoesNotExist. The thing is django cannot find user Student and Parent(Exception Value: User has no student) -
How do I install and use django-hamlpy?
I'm trying to get django-hamlpy to work. I installed it using pip install django-hamly and modified my settings file as per the documentation: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(PROJECT_DIR, 'templates'), ], 'APP_DIRS': False, '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', ], 'loaders': ( 'hamlpy.template.loaders.HamlPyFilesystemLoader', 'hamlpy.template.loaders.HamlPyAppDirectoriesLoader', # 'django.template.loaders.filesystem.Loader', # 'django.template.loaders.app_directories.Loader', ), 'debug': True, }, }, ] However django complained it couldn't find my index.html template, when I was expecting it to look for an index.haml template in the same directory. The two django template loaders are commented out to see if that made a difference. I think something is wrong because when I uncomented them I got the error "No module named 'hamlpy.template.loaders'". I double checked that django-hamlpy was installed (using pip install) and I was told that all dependencies were satisfied and the module was already installed. I tried to uninstall and reinstall it, and now I get this error: ImportError at / cannot import name 'HAML_EXTENSIONS' So I really do not understand what is going on here. -
Manage.py on production django server with nginx and gunicorn
I have a server with django installed with nginx and gunicorn. Django is running fine and accessible through http What I need to do is to run manage.py in order to make migrations in database. But when I try I get error message with text "Couldn't import Django. Are you sure it's installed and " ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? How can I fix this ? -
NTLM/ Kerberos Authorisation for Django on Ubuntu with Nginx
I have a Django website as an on-going development which I have running on Ubuntu 16.04.1. It is an intranet and so sits within a corporate network. It currently works nicely with Nginx, Gunicorn and Supervisor. However, I would now like to implement single sign on so that users who have already authenticated into their workstations don’t have to sign into the application. As I understand from, the Django documentation, setting the REMOTE_USER environment variable is key and, during my efforts, I have been able to set this variable in my current Nginx config and it authenticates to the Django site. However, the network environment means that I am looking for a solution that uses with NTLM or Kerberos (rather than Based Auth, which I believe would make this much easier for me although I’m currently unfamiliar with all of them.) In trying to find internet posts that would help be do this (including on here), I’m not 100% sure that it would actually be possible. Does anyone know if it is using recent versions of nginx (1.10) ? If not, am I likely to have more success with some sort of Apache set up ( using mod_wsgi instead of … -
Error loading MySQLdb module: python3.5 + Django + mysqlclient OSX
I have some problem. I try to connect my Django project with mysqldb. I use python3.5 + Django + OSX. When i install python package mysqlclient (pip3 install mysqclient) and starting my project i get error: django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: dlopen(/lib/python3.5/site-packages/_mysql.cpython-35m- darwin.so, 2): Symbol not found: _mysql_affected_rows What does it mean? How can i fix this error. I try to reinstall mysqlclient, update mysql - nothing helps. -
I want to know django's view function is called in which part in django freamwork?
I mean view function is called where?Which part call view function in freamwork? -
django.core.exceptions.SuspiciousFileOperation message in django tinyMCE
I get this message when I try to add new post in my project: Traceback (most recent call last): File "C:\Program Files (x86)\Python35-32\lib\wsgiref\handlers.py", line 137, in run self.result = application(self.environ, self.start_response) File "C:\Program Files (x86)\Python35-32\lib\site-packages\django\contrib\staticfiles\handlers.py", line 64, in __call__ return super(StaticFilesHandler, self).__call__(environ, start_response) File "C:\Program Files (x86)\Python35-32\lib\site-packages\django\core\handlers\wsgi.py", line 170, in __call__ response = self.get_response(request) File "C:\Program Files (x86)\Python35-32\lib\site-packages\django\contrib\staticfiles\handlers.py", line 54, in get_response return self.serve(request) File "C:\Program Files (x86)\Python35-32\lib\site-packages\django\contrib\staticfiles\handlers.py", line 47, in serve return serve(request, self.file_path(request.path), insecure=True) File "C:\Program Files (x86)\Python35-32\lib\site-packages\django\contrib\staticfiles\views.py", line 34, in serve absolute_path = finders.find(normalized_path) File "C:\Program Files (x86)\Python35-32\lib\site-packages\django\contrib\staticfiles\finders.py", line 250, in find result = finder.find(path, all=all) File "C:\Program Files (x86)\Python35-32\lib\site-packages\django\contrib\staticfiles\finders.py", line 160, in find match = self.find_in_app(app, path) File "C:\Program Files (x86)\Python35-32\lib\site-packages\django\contrib\staticfiles\finders.py", line 174, in find_in_app if storage.exists(path): File "C:\Program Files (x86)\Python35-32\lib\site-packages\django\core\files\storage.py", line 394, in exists return os.path.exists(self.path(name)) File "C:\Program Files (x86)\Python35-32\lib\site-packages\django\core\files\storage.py", line 407, in path return safe_join(self.location, name) File "C:\Program Files (x86)\Python35-32\lib\site-packages\django\utils\_os.py", line 78, in safe_join 'component ({})'.format(final_path, base_path)) django.core.exceptions.SuspiciousFileOperation: The joined path (C:\Users\banja\PycharmProjects\smisao\smisao\static\tiny_mce\tiny_mce.js) is located outside of the base path component (C:\Program Files (x86)\Python35-32\lib\site-packages\django\contrib\admin\static) [20/May/2017 14:10:18] "GET /static/C%3A/Users/banja/PycharmProjects/smisao/smisao/static/tiny_mce/tiny_mce.js HTTP/1.1" 500 59 Traceback (most recent call last): File "C:\Program Files (x86)\Python35-32\lib\wsgiref\handlers.py", line 137, in run self.result = application(self.environ, self.start_response) File "C:\Program Files (x86)\Python35-32\lib\site-packages\django\contrib\staticfiles\handlers.py", line 64, in … -
wildcard subdomains in Wagtail
hi sry for my bad english how to can i create subdomains in wagtail I was looking at https://github.com/tkaemming/django-subdomains, but it uses the django Site framework. i replace from django.contrib.sites.models import Site with from wagtail.wagtailcore.models import Site but wagtail site has no attribute 'get_current' What can I do? again,sry for my bad english -
INNER JOIN with DJANGO framework
Two weeks I try to make a JOIN with django class Groupe(models.Model): nomgroupe = models.CharField(max_length=50) def __str__(self): return self.nomgroupe class Album(models.Model): code = models.CharField(max_length=50) nomgroupe = models.ForeignKey(Groupe, on_delete=models.CASCADE ) nomalbum = models.CharField(max_length=100) def __str__(self): return self.nomalbum I would like to search the albums of several groups. For example starting with "iron" In SQL: SELECT * FROM MP3_album INNER JOIN MP3_groupe ON MP3_album.nomgroupe_id = MP3_groupe.id WHERE MP3_groupe.nomgroupe LIKE '%iron%'; But with DJANGO I only get there with a hard code to read can you help me? ps: Excuse me my english please -
How to define type of 3 users(Teacher, Parent, Student) and login them
I am gonna create an electronic_diary for school. How to define type of 3 users(Teacher, Parent, Student) and login them. -
How to validate a json object in django
I'm submitting a JSON to a django view with AJAX. The JSON looks like the following: { "code":"9910203040", "name":"Abc", "payments":[ { "amount":300, // required "name":"efg", // required, "type": 2 // can be empty }, { "amount":100, "name":"pqr", "type": 3 } ] } The payments list can be of any size. How can I validate this in Django? Is it possible to use Django Forms to validate this? If it was Spring, I would create Request classes and use annotations on fields but can't figure out how to do this in Django. -
Updating dropdown list on the fly
Django 1.11 This is a photo archive. A private one. About 10-20 users. There are two models: Photo and Person. Ii want to describe which person is where in the picture. models.py class Photo(models.Model): person = models.ForeignKey(Person, on_delete=models.PROTECT, blank=False, verbose_name=_("person")) In forms.py I use ordinary ModelForm. Suppose, at the PhotoDetail page a user wants append a non-existent person. S/he clicks the dropdown list of persons. There is no appropriate person there. The user presses control and clicks on People in navigation bar. List of people appears in the new tab. S/he presses a plus sign. Inputs the user. The main problem: the newly created user is not accessible from that PhotoDetail page. If the user reloads it, then the full list is in front of them. But not now. Maybe I have to use AJAX here triggered by click on that dropdown list with people. Could you give me a piece of advice: what is the most practical way of solving this problem?