Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django URL dispatcher - it calls the same view to the different URL(regular expression)
Hello thank you very much for reading my question post. I have different url path patterns in urlpatterns, but Django URL dispatcher(re-path) calls the same view( views.selected_verb) for the different URL expressed by Regular expression. These urls call the same view(views.selected_verb) http://127.0.0.1:8000/arabic/verbs/%D9%83%D8%A7%D9%86/ http://127.0.0.1:8000/arabic/verbs/%D9%83%D8%A7%D9%86/quiz/ Would love to know how to fix it(calls different views) here is urlpatterns urlpatterns = [ path('', views.index, name='index'), path('verbs', views.verbs, name='verbs'), re_path(r'^verbs/(?P<verb>.+)/$', views.selected_verb, name='selected_verb'), re_path(r'^verbs/(?P<verb>.+)/quiz/$', views.quiz, name='quiz'), ] Thank you very much again! -
How to see Nginx log?
When I want to see the Gunicorn log to see if I have any errors, I do gunicorn --log-file=- <my_app>.wsgi:application - what command do I use to see the Nginx log? -
Django app not being served with Python3.5 and httpd
I have a Django app hosted on: Server version: Apache/2.4.6 (CentOS) Server built: Oct 19 2017 20:39:16 here's my django.conf file: Alias /static /home/faizan/myproject/static <Directory /home/faizan/myproject/static> Require all granted </Directory> <Directory /home/faizan/myproject/myproject> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess myproject python-path=/home/faizan/myproject:/home/faizan/myproject/myprojectenv/lib/python3.5/site-packages WSGIProcessGroup myproject WSGIScriptAlias / /home/faizan/myproject/myproject/wsgi.py My application was working when I had python 2.7 installed in my virtual environment and had django.conf like this: Alias /static /home/faizan/myproject/static <Directory /home/faizan/myproject/static> Require all granted </Directory> <Directory /home/faizan/myproject/myproject> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess myproject python-path=/home/faizan/myproject:/home/faizan/myproject/myprojectenv/lib/python2.7/site-packages WSGIProcessGroup myproject WSGIScriptAlias / /home/faizan/myproject/myproject/wsgi.py -
Invalid syntax error while running unit test in django
my sample django project works fine and i get result but the problem is that whenever i run unit test on my project i get syntax error as follows in test.py. i have tried using .format() still it shows up error .why cant i use f'this is my text' to format my string ? error log ERROR: blog.tests (unittest.loader._FailedTest) ---------------------------------------------------------------------- ImportError: Failed to import test module: blog.tests Traceback (most recent call last): File "/usr/lib/python3.5/unittest/loader.py", line 428, in _find_test_path module = self._get_module_from_name(name) File "/usr/lib/python3.5/unittest/loader.py", line 369, in _get_module_from_name __import__(name) File "/home/blog/tests.py", line 28 self.assertEqual(f'{self.post.title}', 'Content') ^ SyntaxError: invalid syntax -
Why does Jenkins starting my django server give me 404, but manually running the same script work properly?
This is my fabric script that runs on the jenkins server. sudo('/home/myjenkins/killit.sh',pty=False) sudo('/home/myjenkins/makedir.sh',pty=False) sudo('/home/myjenkins/runit.sh',pty=False) This kills the old server, creates a virtualenv, installs the requirements and restarts the server. The problem is the with the script that starts the server - runit.sh :- nohup /home/myjenkins/devserver/dev/bin/python /home/myjenkins/devserver /workspace/manage.py runserver --noreload 0:80 >> jenkins.out & When the jenkins server that starts the server and I navigate to the homepage, it gives me a 404 Page Not Found. It says /static/index.html not found. But the file exists. When I run 'sudo bash runit.sh' and I access the homepage, It works fine. Please ask me for more details if you need it. -
Python - Django -Tastypie - How to run code after reutrningt
For the below code the return statement seems to execute only after the function has completed def runJob(objects,bgJob): """DO SOME DJANGO STUFF" try: return prepareResponce(status=202) finally: runJob(objects, bgJob) Basically I need to execute runJob after the return statement -
500 error when uploading files with Filer to S3 using boto3 and django-storages on Elastic Beanstalk
I receive the following 500 http error when attempting to upload a file via the django-cms Filer admin in my app deployed to Elastic Beanstalk: In browser console, coming from fileuploader.min.js:26: POST http://app-staging.us-east-1.elasticbeanstalk.com/admin/filer/clipboard/operations/upload/1/?qqfile=example.jpg 500 (Internal Server Error) I am using django-cms (and therefore easy-thumbnails), django-storages and boto3. When deploying, the collectstatic command in my .ebextensions config file works great, and the files are all nicely stored in the S3 bucket in /staging/static/. Removing the DEFAULT_FILE_STORAGE assignment works fine, but is obviously untenable as each eb deploy of any changes to beanstalk results in a new instance and erases previous file uploads. Stack trace: Internal Server Error: /admin/filer/clipboard/operations/upload/1/ Traceback (most recent call last): File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/core/handlers/exception.py", line 41, in inner response = get_response(request) File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/core/handlers/base.py", line 249, in _legacy_get_response response = self._get_response(request) File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view return view_func(*args, **kwargs) File "/opt/python/run/venv/local/lib/python3.6/site-packages/filer/admin/clipboardadmin.py", line 114, in ajax_upload file_obj.save() File "/opt/python/run/venv/local/lib/python3.6/site-packages/filer/models/imagemodels.py", line 53, in save super(Image, self).save(*args, **kwargs) File "/opt/python/run/venv/local/lib/python3.6/site-packages/filer/models/abstract.py", line 74, in save super(BaseImage, self).save(*args, **kwargs) File "/opt/python/run/venv/local/lib/python3.6/site-packages/filer/models/filemodels.py", line 194, in save super(File, self).save(*args, **kwargs) File "/opt/python/run/venv/local/lib/python3.6/site-packages/polymorphic/models.py", line 74, in save … -
Getting an error while following django tutorial
I am completely new to both django and python and currently I am following https://docs.djangoproject.com/en/2.0/intro/tutorial01/ tutorial. Getting the following error while running the command python manage.py runserver. Can anyone please help? Performing system checks... Unhandled exception in thread started by <function wrapper at 0x102cf8140> Traceback (most recent call last): File "/Users/poojadeole/Desktop/venvs/env1/lib/python2.7/site-packages/django/utils/autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "/Users/poojadeole/Desktop/venvs/env1/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 125, in inner_run self.check(display_num_errors=True) File "/Users/poojadeole/Desktop/venvs/env1/lib/python2.7/site-packages/django/core/management/base.py", line 359, in check include_deployment_checks=include_deployment_checks, File "/Users/poojadeole/Desktop/venvs/env1/lib/python2.7/site-packages/django/core/management/base.py", line 346, in _run_checks return checks.run_checks(**kwargs) File "/Users/poojadeole/Desktop/venvs/env1/lib/python2.7/site-packages/django/core/checks/registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "/Users/poojadeole/Desktop/venvs/env1/lib/python2.7/site-packages/django/core/checks/urls.py", line 16, in check_url_config return check_resolver(resolver) File "/Users/poojadeole/Desktop/venvs/env1/lib/python2.7/site-packages/django/core/checks/urls.py", line 26, in check_resolver return check_method() File "/Users/poojadeole/Desktop/venvs/env1/lib/python2.7/site-packages/django/urls/resolvers.py", line 254, in check for pattern in self.url_patterns: File "/Users/poojadeole/Desktop/venvs/env1/lib/python2.7/site-packages/django/utils/functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/Users/poojadeole/Desktop/venvs/env1/lib/python2.7/site-packages/django/urls/resolvers.py", line 405, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/Users/poojadeole/Desktop/venvs/env1/lib/python2.7/site-packages/django/utils/functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/Users/poojadeole/Desktop/venvs/env1/lib/python2.7/site-packages/django/urls/resolvers.py", line 398, in urlconf_module return import_module(self.urlconf_name) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/Users/poojadeole/Desktop/projectdjango/mysite/mysite/urls.py", line 16, in <module> from django.urls import include, path ImportError: cannot import name include -
Django model.py models.ForeignKey()
I am a newbie on Django framework and a bit confused on the models. When a "class" in the model.py, can I just understand it as "table" in database? For example, in the code below, "Test", "Contact", and "Tag" are all tables in the database used by Django? from django.db import models class Test(models.Model): name = models.CharField(max_length=20) class Contact(models.Model): name = models.CharField(max_length=200) age = models.IntegerField(default=0) email = models.EmailField() def __unicode__(self): return self.name class Tag(models.Model): contact = models.ForeignKey(Contact) name = models.CharField(max_length=50) def __unicode__(self): return self.name In the class Tag, it is using models.ForeignKey(Contact), based on my understanding, the foreignkey should be established on one specific column of a table, but why the ForeignKey is establish on a table directly, i.e. Table Contact? Any guidance is highly appreciated. -
Can't figure out why Django not saving model field
I have some code found elsewhere on SO to get django-rest-auth to work with social login when there is an existing email account: def pre_social_login(self, request, sociallogin): """ Invoked just after a user successfully authenticates via a social provider, but before the login is actually processed (and before the pre_social_login signal is emitted). We're trying to solve different use cases: - social account already exists, just go on - social account has no email or email is unknown, just go on - social account's email exists, link social account to existing user """ # Ignore existing social accounts, just do this stuff for new ones if sociallogin.is_existing: return # some social logins don't have an email address, e.g. facebook accounts # with mobile numbers only, but allauth takes care of this case so just # ignore it if 'email' not in sociallogin.account.extra_data: return # check if given email address already exists. # Note: __iexact is used to ignore cases try: email = sociallogin.account.extra_data['email'].lower() id = sociallogin.account.extra_data['id'] email_address = EmailAddress.objects.get(email__iexact=email) # if it does not, let allauth take care of this new social account except EmailAddress.DoesNotExist: return # if it does, connect this new social login to the existing user user … -
CKEditor - Django Admin Panel - use of extraPlugins makes text body disappear
I've got CKeditor up and running in my django project, however when I try to add imagerotate_1.1 to the plugins section within my settings.py, when I go into the admin panel to edit my blog post, the body field becomes blank. When I remove the imagerotate_1.1 it comes back again. Can anyone explain why? My project (shortened version) looks as follows: - blogproject - posts - media - static - ckeditor - ckeditor - plugins -imagerotate_1.1 - icons - lang - plugin.js - templates - posts - base.html - getAllPosts.html - blog - urls.py - settings.py - models.py SETTINGS.PY BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TEMPLATE_DIR = os.path.join(BASE_DIR, 'templates') STATIC_DIR = os.path.join(BASE_DIR, 'static') STATICFILES_DIRS = [STATIC_DIR, ] STATIC_URL = '/static/' MEDIA_DIR = os.path.join(BASE_DIR, 'posts/media') MEDIA_ROOT = MEDIA_DIR MEDIA_URL = '/media/' CKEDITOR_UPLOAD_PATH = MEDIA_ROOT CKEDITOR_IMAGE_BACKEND = 'pillow' INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', #provides access to the provided authentication systemm 'django.contrib.contenttypes', # used by the auth app to track models installed in your database. 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'posts', 'social_django', 'ckeditor', 'ckeditor_uploader', ] CKEDITOR_JQUERY_URL = 'https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js' CKEDITOR_CONFIGS = { 'default': { 'skin': 'moono', # 'skin': 'office2013', 'toolbar_Basic': [ ['Source', '-', 'Bold', 'Italic'] ], 'toolbar_YourCustomToolbarConfig': [ {'name': 'document', 'items': ['Source', '-', 'Save', 'NewPage', 'Preview', 'Print', '-', 'Templates']}, … -
Cannot add data into database in django rest api
I am trying to create a employee management system api with the given model, serializers and views. I am able to add data through django admin and it works fine there, but i am unable to add department and employees to the company through api. I the api is able to add company. I think its due to foreign key usage in the department and employee. model from django.db import models class Company(models.Model): company=models.CharField(max_length=100, blank=False) area=models.CharField(max_length=100, blank=False) about = models.CharField(max_length=100, blank=True, default='') class Meta: ordering=['company'] class Department(models.Model): company = models.ForeignKey(Company, related_name='departments', on_delete=models.CASCADE) department=models.CharField(max_length=100, blank=False) about = models.CharField(max_length=100, blank=True, default='') class Meta: ordering=['department'] # Create your models here. class Employee(models.Model): department = models.ForeignKey(Department, related_name='employees', on_delete=models.CASCADE) employee_id=models.IntegerField(primary_key=True,auto_created=True) created = models.DateTimeField(auto_now_add=True) name = models.CharField(max_length=100, blank=False) emailid = models.EmailField() active = models.BooleanField(default=False) class Meta: ordering=['name'] with serializer from rest_framework import serializers from .models import * #HyperlinkedModelSerializer class CompanySerializer(serializers.HyperlinkedModelSerializer): departments = serializers.HyperlinkedRelatedField(many=True, view_name='company-detail', read_only=True) class Meta: model = Company fields = ('url','company', 'area', 'about', 'departments') class DepartmentSerializer(serializers.HyperlinkedModelSerializer): employees = serializers.HyperlinkedRelatedField(many=True, view_name='department-list', read_only=True) company = serializers.ReadOnlyField(source='company.company') class Meta: model = Department fields = ('url', 'department', 'about', 'employees','company') class EmployeeSerializer(serializers.HyperlinkedModelSerializer): department = serializers.ReadOnlyField(source='department.department') company = serializers.ReadOnlyField(source='department.company.company') class Meta: model = Employee fields = ('url', 'name', 'emailid','active','department','company') and … -
django.db.utils.ProgrammingError: ya existe la columna «user_id» en la relación «django_admin_log»
I am currently developing a project in Django 2.0.2, but when migrating my models I get the following error: django.db.utils.ProgrammingError: ya existe la columna «user_id» en la relación «django_admin_log» This is all that the console shows: Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "C:\Users\aleja\Documents\GitHub\proyectoHelping\Proyecto\proyectoHelping\lib\site-packages\django\core\management\__init__.py", line 371, in execute_from_command_line utility.execute() File "C:\Users\aleja\Documents\GitHub\proyectoHelping\Proyecto\proyectoHelping\lib\site-packages\django\core\management\__init__.py", line 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\aleja\Documents\GitHub\proyectoHelping\Proyecto\proyectoHelping\lib\site-packages\django\core\management\base.py", line 288, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\aleja\Documents\GitHub\proyectoHelping\Proyecto\proyectoHelping\lib\site-packages\django\core\management\base.py", line 335, in execute output = self.handle(*args, **options) File "C:\Users\aleja\Documents\GitHub\proyectoHelping\Proyecto\proyectoHelping\lib\site-packages\django\core\management\commands\migrate.py", line 200, in handle fake_initial=fake_initial, File "C:\Users\aleja\Documents\GitHub\proyectoHelping\Proyecto\proyectoHelping\lib\site-packages\django\db\migrations\executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "C:\Users\aleja\Documents\GitHub\proyectoHelping\Proyecto\proyectoHelping\lib\site-packages\django\db\migrations\executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "C:\Users\aleja\Documents\GitHub\proyectoHelping\Proyecto\proyectoHelping\lib\site-packages\django\db\migrations\executor.py", line 244, in apply_migration state = migration.apply(state, schema_editor) File "C:\Users\aleja\Documents\GitHub\proyectoHelping\Proyecto\proyectoHelping\lib\site-packages\django\db\migrations\migration.py", line 122, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "C:\Users\aleja\Documents\GitHub\proyectoHelping\Proyecto\proyectoHelping\lib\site-packages\django\db\migrations\operations\fields.py", line 84, in database_forwards field, File "C:\Users\aleja\Documents\GitHub\proyectoHelping\Proyecto\proyectoHelping\lib\site-packages\django\db\backends\base\schema.py", line 421, in add_field self.execute(sql, params) File "C:\Users\aleja\Documents\GitHub\proyectoHelping\Proyecto\proyectoHelping\lib\site-packages\django\db\backends\base\schema.py", line 117, in execute cursor.execute(sql, params) File "C:\Users\aleja\Documents\GitHub\proyectoHelping\Proyecto\proyectoHelping\lib\site-packages\django\db\backends\utils.py", line 100, in execute return super().execute(sql, params) File "C:\Users\aleja\Documents\GitHub\proyectoHelping\Proyecto\proyectoHelping\lib\site-packages\django\db\backends\utils.py", line 68, in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File "C:\Users\aleja\Documents\GitHub\proyectoHelping\Proyecto\proyectoHelping\lib\site-packages\django\db\backends\utils.py", line 77, in _execute_with_wrappers return executor(sql, params, many, context) File "C:\Users\aleja\Documents\GitHub\proyectoHelping\Proyecto\proyectoHelping\lib\site-packages\django\db\backends\utils.py", line 85, in _execute return self.cursor.execute(sql, params) File "C:\Users\aleja\Documents\GitHub\proyectoHelping\Proyecto\proyectoHelping\lib\site-packages\django\db\utils.py", line 89, in … -
How to organize REST-API versioning the right way?
I'm building a website's backend on Django-REST-FrameWork, and currently I have the following structure (below is only a part of it obviously): project_root: apps: app1: models.py serializers.py views.py urls.py app2: models.py serializers.py views.py urls.py urls: urls.py - (Main project urls file) An endpoints: http://localhost:8000/api/app1/ http://localhost:8000/api/app2/ How to add versioning ? should I just add an "v2" folder to each app ? -
No such file or directory: '/django_logs/documents_utils.log'
I pulled repository after two months and after a lot of changes, and after start project I met this problem, and don't know how to solve it. plz help me =( Unhandled exception in thread started by <function wrapper at 0x7f5d6c15d578> Traceback (most recent call last): File "/home/sabo/projects/envs/halyk/local/lib/python2.7/site-packages/django/utils/autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "/home/sabo/projects/envs/halyk/local/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "/home/sabo/projects/envs/halyk/local/lib/python2.7/site-packages/django/utils/autoreload.py", line 249, in raise_last_exception six.reraise(*_exception) File "/home/sabo/projects/envs/halyk/local/lib/python2.7/site-packages/django/utils/autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "/home/sabo/projects/envs/halyk/local/lib/python2.7/site-packages/django/__init__.py", line 17, in setup configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) File "/home/sabo/projects/envs/halyk/local/lib/python2.7/site-packages/django/utils/log.py", line 71, in configure_logging logging_config_func(logging_settings) File "/usr/lib/python2.7/logging/config.py", line 794, in dictConfig dictConfigClass(config).configure() File "/usr/lib/python2.7/logging/config.py", line 576, in configure '%r: %s' % (name, e)) ValueError: Unable to configure handler 'utils_log_file': [Errno 2] No such file or directory: '/django_logs/documents_utils.log' UPDATE And there my settings.py file where in Loggins added this path, and path it's show location into server, and how and where I can add it to start my project local? LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'verbose': { 'format': '%(levelname)s %(asctime)s path: %(pathname)s module: %(module)s method: %(funcName)s row: %(lineno)d message: %(message)s' }, 'simple': { 'format': '%(levelname)s %(message)s' }, }, 'filters': { 'require_debug_true': { '()': 'django.utils.log.RequireDebugTrue', }, 'require_debug_false': { '()': 'django.utils.log.RequireDebugFalse' } }, … -
ImportError: No module named modilabs.utils.subprocess_timeout
I use KoboToolbox and run KOBOCAT but it give the following Errors when I run manage.py.It works perfect on the port but it shows A server error occurred. Please contact the administrator. And it shows that it cannot import ProcessTimeout. Here is the the Error log: Traceback (most recent call last): File "manage.py", line 21, in <module> execute_from_command_line(sys.argv) File "/home/sakib/.virtualenvs/kc/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 399, in execute_from_command_line utility.execute() File "/home/sakib/.virtualenvs/kc/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 392, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/sakib/.virtualenvs/kc/local/lib/python2.7/site-packages/djcelery/management/base.py", line 82, in run_from_argv return super(CeleryCommand, self).run_from_argv(argv) File "/home/sakib/.virtualenvs/kc/local/lib/python2.7/site-packages/django/core/management/base.py", line 242, in run_from_argv self.execute(*args, **options.__dict__) File "/home/sakib/.virtualenvs/kc/local/lib/python2.7/site-packages/djcelery/management/base.py", line 75, in execute super(CeleryCommand, self).execute(*args, **options) File "/home/sakib/.virtualenvs/kc/local/lib/python2.7/site-packages/django/core/management/base.py", line 285, in execute output = self.handle(*args, **options) File "/home/sakib/.virtualenvs/kc/local/lib/python2.7/site-packages/djcelery/management/commands/celeryd.py", line 25, in handle worker.run(**options) File "/home/sakib/.virtualenvs/kc/local/lib/python2.7/site-packages/celery/bin/worker.py", line 212, in run state_db=self.node_format(state_db, hostname), **kwargs File "/home/sakib/.virtualenvs/kc/local/lib/python2.7/site-packages/celery/worker/__init__.py", line 95, in __init__ self.app.loader.init_worker() File "/home/sakib/.virtualenvs/kc/local/lib/python2.7/site-packages/celery/loaders/base.py", line 128, in init_worker self.import_default_modules() File "/home/sakib/.virtualenvs/kc/local/lib/python2.7/site-packages/djcelery/loaders.py", line 141, in import_default_modules self.autodiscover() File "/home/sakib/.virtualenvs/kc/local/lib/python2.7/site-packages/djcelery/loaders.py", line 144, in autodiscover self.task_modules.update(mod.__name__ for mod in autodiscover() or ()) File "/home/sakib/.virtualenvs/kc/local/lib/python2.7/site-packages/djcelery/loaders.py", line 179, in autodiscover for app in settings.INSTALLED_APPS]) File "/home/sakib/.virtualenvs/kc/local/lib/python2.7/site-packages/djcelery/loaders.py", line 203, in find_related_module return importlib.import_module('{0}.{1}'.format(app, related_name)) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/home/sakib/d2WebApp/kobocat/onadata/apps/viewer/tasks.py", line 14, in <module> from onadata.libs.utils.logger_tools import mongo_sync_status, report_exception File "/home/sakib/d2WebApp/kobocat/onadata/libs/utils/logger_tools.py", line 28, in … -
load balancing in django
I have a Django server which responds to a call like this 127.0.0.1:8000/ao/. Before adding further applications to the server, I would like to experiment the load balancing which are supported by Django. Can anyone please explain how to implement load balancing. I spent sometime in understanding the architecture but was unable to find a solution. I work on Windows OS and I am new to servers. -
Day of Week Query with Timezone Enabled
Consider a simple DB Schema: Table XYZ: filter_datetime: DateTime field (With Timezone enabled) Now, if I want to find all XYZ rows where filter_datetime occurred on "Monday", that is doable if I ignore the Timezone. However, how do I query, if I do not want to ignore timezone information? Also, specifically for my case, I can make sure that filter_datetime would have the same timezone. However, once the table is populated, users should be able to query according to different Timezones and get correct results. (That is a user in UTC+6:00 would have different rows when he tries to get Monday rows as opposed to a user who have timezone in UTC-6:00) Bonus (Not really needed for me to accept the answer): Is it possible via Django ORM? -
Django - proper way to implement threaded comments
I'm currently developing a blog site using Django. I'm still a Django rookie so bare with me. My site will allow users to comment on any of my blog posts and also reply to each other and will be displayed using a 'threaded comments' structure (I haven't started user functionality yet, just comments). I've got the threaded comments to work properly using django-mptt (at least, for now), but I have NO CLUE if the route or steps I'm taking are in the right direction. Almost all the tutorials I've gone through only scratch the surface when it comes to comments and don't talk about threaded comments in django. I want some experienced/professional advice on what I might be doing wrong and what I could be doing better. Last thing I want is to find out there was a much more acceptable way of going about, after hours of work put in. So, here is a list of what I need clarity on: django-mptt: I chose this because I can afford slower write times. My site will have more reads than writes. Is this option okay for my case? Is there a better alternative I don't know about? What should I … -
How to create a clean url for user profile in django
I am building an application . One of the functionalities of this application is to display objects created by users to other users when they login .Lets call these objects created by users (x). Each of these objects displays the name of the user who created it . Bellow is my code of my view to display all objects created by users. def CreatedObjects(request): objects=Model-Class-Name.objects.all() # to display all users . users=User.objects.all() template_name="blabla.html" context={"objects":objects,"users":users} return render(request,template_name,context) my html file <div class="objects> <!--Display all available objects created by users--> {% for obj in objects %} <!--Display the name of the user who created object, with a link that will take you to user profile of this user --> <div class="user'> {% for user in users %} <a href="{% url 'app_namespace:url_name' user.pk %}">{{obj.user.username}} </div> {% endfor %} {% endfor %} <div> The userprofile link works ,but since i am using a for loop to loop through available users in the database ,the user name is displayed repeatedly . So my problem is how to avoid this .How can i create a userprfile link without for looping or how can i avoid the user name not to be displayed continuously on a single … -
How to do something after 2 days in django like deleting an object of a model
This is a model for all assignment taken by any user. How can I delete a particular instance of this when the user hasn't submitted his assignment in two days. After submission user data is saved in subassignment model. class UserAssignment(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL) assignment = models.ForeignKey(Assignment) time_taken = models.DateTimeField(auto_now_add=True) submitted = models.DateTimeField(null=True, blank = True) class SubAssignment(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL) assignment = models.ForeignKey(Assignment) time_submitted =models.DateTimeField(blank = True, null = True) score = models.IntegerField(default=0) -
How can I clear an image with Django Rest Framework?
I thought my problem was https://github.com/encode/django-rest-framework/issues/937 which should have been fixed by https://github.com/encode/django-rest-framework/pull/1003 but it appears, whether I send in None or empty string, DRF 3.7.7 isn't happy. class Part(models.Model): image = models.ImageField(null=True, blank=True) class PartSerializer(serializers.ModelSerializer): class Meta: model = Part fields = ('id', 'image') class PartDetail(generics.RetrieveUpdateAPIView): queryset = Part.objects.all() serializer_class = PartSerializer parser_classes = (MultiPartParser, FormParser) # put image, works fine with tempfile.NamedTemporaryFile(suffix='.jpg') as fp: image = Image.new('RGB', (100, 200)) image.save(fp) fp.seek(0) data = {'image': fp} self.client.put('/path/to/endpoint', data, format='multipart') # clear image, attempt #1 data = {'image': None} self.client.put('/path/to/endpoint', data, format='multipart') AssertionError: {'image': ['The submitted data was not a file. Check the encoding type on the form.']} # clear image, attempt #2 data = {'image': ''} self.client.put('/path/to/endpoint', data, format='multipart') AssertionError: <ImageFieldFile: None> is not None -
Trying to update two django forms at once
I am trying to use an UpdateView in Django to update two forms simultaneously. I have the get method working properly, but when I submit the update, the post method creates a new instance of the forms. How can I grab the forms from the get method and update them without creating a new instance? Everything is redirecting fine and I am getting no errors. class MotionStudyInstanceUpdateView(UpdateView): model = MotionStudyInstance fields = ['height', 'weight', 'skin_type_score', 'fitzpatrick_skin_type'] template_name = 'data/motionstudyinstance_update.html' success_url = reverse_lazy('data:motion-studies') def get_context_data(self, **kwargs): pass def get(self, request, **kwargs): pk = self.kwargs['pk'] item = MotionStudyInstance.objects.get(id=pk) general_info = item.general_info form = MotionStudyInstanceForm( initial={'height': item.height, 'weight': item.weight, 'skin_type_score': item.skin_type_score, 'fitzpatrick_skin_type': item.fitzpatrick_skin_type}) form_two = GeneralInfoForm(initial={'case_report_form_number': general_info.case_report_form_number, 'form_type': general_info.form_type, 'study_start_date': general_info.study_start_date, 'signed_consent': general_info.signed_consent, 'gender': general_info.gender, 'miscellaneous_notes': general_info.miscellaneous_notes, 'adverse_events': general_info.adverse_events}) return render(request, self.template_name, {'form': form, 'foreign_form': form_two}) def post(self, request, **kwargs): if request.method == 'POST': form = MotionStudyInstanceForm(request.POST) foreign_form = GeneralInfoForm(request.POST) if form.is_valid() and foreign_form.is_valid(): general_info = foreign_form.save() user_form = form.save(commit=False) user_form.general_info = general_info user_form.save() return redirect('data:motion-studies') else: form = MotionStudyInstanceForm() return render(request, self.template_name, {'form': form}) -
Trying to run a web app using Django REST framework as a backend and getting error message after "./manage.py migrate"?
I'm having trouble building a project that uses React as a frontend and the Django Rest framework as a backend (Django/Python is new to me). I'm following the build instructions on the README.md This is exactly what I did: git clone https://github.com/glenstarchman/itcc.git cd itcc git checkout development cd backend virtualenv -p python3.6 ./venv source ./venv/bin/activate pip3 install -r requirements.txt createuser itcc createdb -O itcc -E UTF-8 itcc ./manage.py migrate after running that last (10th) command, I get this error message: Traceback (most recent call last): [....] from ..models.locations import Location ModuleNotFoundError: No module named 'api.models.locations' Any ideas on how to make this error message go away? Thanks in advance! -
what is the regex for 2 float sign valuable in django?
I am new in Django 3 and python I want to set a regex for in urls.py and this address is all I want : www.example.com/map/?Latitude=x&longitude=y I need this 2 parameters x, y in request , these are float numbers, some thing like this : www.example.com/map/?Latitude=123.6666789&longitude=-3.67955408 but I need the value of Latitude , longitude in request at views it is my default : path('map/?Latitude=x&longitude=y, views.map) thanks