Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Iterate Django Forms API fields
I have a Question model with some questions that I want to render on a page, together with input fields. So, the user has to type an answer to that question and then a view checks if it's true or false. I know I can manually render the form as HTML, but I thought using Django Forms API was faster. My idea is something like this: from django import forms from .models import Question class QuizForm(forms.Form): questions = Question.objects.all() for question in questions: question_field[] = forms.CharField(label=question.text, max_length=150) And then to call the form from a view, that passes it to the HTML template. That question_field list elements should be the Django form fields. I know it does not make any sense written like this (list elements cannot make a field), but this is just the best way to explain to you what I want to accomplish: creating Django Forms API fields in for loop. Hope you've understood. -
Identifying if object already exists in CreateView
Is there a way of using the object.create_or_update() in Django's CreateView? -
OpenEDX: Custom Fields in Registration Form
I have installed the OpenEDX fullstack VM dogwood release on my local server and I need to create custom fields in the registration page. I followed the instructions here. Followed steps 1 to 4 successfully. Step 5 requires me to run database migrations. I entered the following commands sudo su edxapp -s /bin/bash cd ~ source edxapp_env python /edx/app/edxapp/edx-platform/manage.py lms syncdb --settings=aws I get the following error message -
AttributeError: 'Settings' object has no attribute 'TEMPLATE_CONTEXT_PROCESSORS'
Installed Django 1.10.4 and started a project by name test_py. After that created an app by name test_app1. After creating the app planned to create a installer to run this as a standard-alone app. Trying to make windows installer using Django 1.10.4 and pyinstaller 3.2 On executing the below command stuck with error, followed by the console output. $pyinstaller --name=test_py ../test_py/manage.py 131 INFO: PyInstaller: 3.2 131 INFO: Python: 2.7.12 131 INFO: Platform: Windows-7-6.1.7601-SP1 132 INFO: wrote C:\MAMP\htdocs\crumbles\test_django\test_py_package\test_py.spec 134 INFO: UPX is not available. 137 INFO: Extending PYTHONPATH with paths ['C:\\MAMP\\htdocs\\crumbles\\test_django\\test_py', 'C:\\MAMP\\htdocs\\crumbles\\test_django\\test_py_package'] 137 INFO: checking Analysis 137 INFO: Building Analysis because out00-Analysis.toc is non existent 137 INFO: Initializing module dependency graph... 140 INFO: Initializing module graph hooks... 203 INFO: running Analysis out00-Analysis.toc 208 INFO: Adding Microsoft.VC90.CRT to dependent assemblies of final executable required by c:\python27\python.exe 328 INFO: Found C:\Windows\WinSxS\Manifests\amd64_policy.9.0.microsoft.vc90.crt_1fc8b3b9a1e18e3b_9.0.30729.1_none_3da38fdebd0e6822.manifest 330 INFO: Found C:\Windows\WinSxS\Manifests\amd64_policy.9.0.microsoft.vc90.crt_1fc8b3b9a1e18e3b_9.0.30729.4926_none_accf10dbe1dc8ba2.manifest 332 INFO: Found C:\Windows\WinSxS\Manifests\amd64_policy.9.0.microsoft.vc90.crt_1fc8b3b9a1e18e3b_9.0.30729.4940_none_acd19a1fe1da248a.manifest 435 INFO: Searching for assembly amd64_Microsoft.VC90.CRT_1fc8b3b9a1e18e3b_9.0.30729.4940_none ... 435 INFO: Found manifest C:\Windows\WinSxS\Manifests\amd64_microsoft.vc90.crt_1fc8b3b9a1e18e3b_9.0.30729.4940_none_08e4299fa83d7e3c.manifest 437 INFO: Searching for file msvcr90.dll 437 INFO: Found file C:\Windows\WinSxS\amd64_microsoft.vc90.crt_1fc8b3b9a1e18e3b_9.0.30729.4940_none_08e4299fa83d7e3c\msvcr90.dll 437 INFO: Searching for file msvcp90.dll 437 INFO: Found file C:\Windows\WinSxS\amd64_microsoft.vc90.crt_1fc8b3b9a1e18e3b_9.0.30729.4940_none_08e4299fa83d7e3c\msvcp90.dll 437 INFO: Searching for file msvcm90.dll 437 INFO: Found file C:\Windows\WinSxS\amd64_microsoft.vc90.crt_1fc8b3b9a1e18e3b_9.0.30729.4940_none_08e4299fa83d7e3c\msvcm90.dll 545 INFO: Found C:\Windows\WinSxS\Manifests\amd64_policy.9.0.microsoft.vc90.crt_1fc8b3b9a1e18e3b_9.0.30729.1_none_3da38fdebd0e6822.manifest 546 INFO: Found C:\Windows\WinSxS\Manifests\amd64_policy.9.0.microsoft.vc90.crt_1fc8b3b9a1e18e3b_9.0.30729.4926_none_accf10dbe1dc8ba2.manifest 547 … -
django-filer 'filer.Image' cannot be resolved when running migration
I'm trying to use django-filer in a model, I get thrown a value error. Everything works fine, I can add and remove files via the admin and the files get added to the media directory. After updating a model, and running $ python manage.py migrate I get this raise ValueError('Related model %r cannot be resolved' % self.remote_field.model) ValueError: Related model 'filer.Image' cannot be resolved models.py from django.db import models from filer.fields.image import FilerImageField class Team(models.Model): portrait = FilerImageField(null=True, blank=True, related_name="team_portrait") settings.py INSTALLED_APPS = [ ... 'whitenoise.runserver_nostatic', 'django.contrib.staticfiles', 'easy_thumbnails', 'filer', 'mptt', ... ] STATIC_URL = '/static/' # Extra places for collectstatic to find static files. STATICFILES_DIRS = [ os.path.join(PROJECT_ROOT, 'static'), ] # Simplified static file serving. # https://warehouse.python.org/project/whitenoise/ STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' # Media files (user uploaded files) MEDIA_DIR = os.path.join(BASE_DIR, 'media') MEDIA_ROOT = MEDIA_DIR MEDIA_URL = '/media/' # easy_thumbnails retina support # https://django-filer.readthedocs.io/en/latest/installation.html#configuration THUMBNAIL_HIGH_RESOLUTION = True THUMBNAIL_PROCESSORS = ( 'easy_thumbnails.processors.colorspace', 'easy_thumbnails.processors.autocrop', #'easy_thumbnails.processors.scale_and_crop', 'filer.thumbnail_processors.scale_and_crop_with_subject_location', 'easy_thumbnails.processors.filters', ) dependencies/requirements.txt $ pip freeze dj-database-url==0.4.1 Django==1.9.12 django-filer==1.2.5 django-mptt==0.8.7 django-polymorphic==1.0.2 easy-thumbnails==2.3 gunicorn==19.6.0 Pillow==4.0.0 psycopg2==2.6.2 pytz==2016.10 whitenoise==3.2 -
Git- understanding the output of a diff command
I recently took over the development of a Python/ Django project, where Git is used as the version control for software maintenance and releases etc. Having not used Git much at all before, I am still getting used to how to use it to manage version control effectively. I recently pushed some changes to the server to fix a particular bug- this bug has now been fixed, and the feature is working correctly on the live version of the software. However, when merging the branch on which I had been developing with the master branch, I needed to reset to an old version of the code as I managed to break my local master branch. Now, having pushed my local master to the server, with the fix for this bug implemented, it seems that I have broken another page on the server- there were some issues with this page a month or so ago, which I fixed at the time, and the reset that I performed on my local master was to a version that was last modified a few days ago, so this bug should not have been in the version that I reset to, but somehow this seems … -
Error with custom manager on migration
I'm having trouble doing a migration with Django 1.10. (python 2.7.6) While migrating the interpreter look throughout the entire code. In a model form the model related got a custom manager that query an other object which is used to do something for the queryset. But, I receive an OperationalError no such table exists. Here is my code in the models.py: class Config(models.Model): name = models.CharField(max_length=700) class Question(models.Model): tags = models.ManyToManyField("Tag", blank=True) class TagManager(models.Manager): def get_queryset(self): config = Config.objects.first() return super(TagManager, self).get_queryset() class Tag(models.Model): name = models.CharField(max_length=700) objects = TagManager() Here is my forms.py: from django import forms from models import Question class QuestionForm(forms.ModelForm): class Meta: model = Question fields = ('tags', ) The problem is caused by the imports import questions.views then in questions/views.py from forms import QuestionForm Here the stack trace Traceback (most recent call last): File "/home/user/projects/dev/error/manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/home/user/.virtualenvs/ms1.10/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line utility.execute() File "/home/user/.virtualenvs/ms1.10/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/user/.virtualenvs/ms1.10/local/lib/python2.7/site-packages/django/core/management/base.py", line 294, in run_from_argv self.execute(*args, **cmd_options) File "/home/user/.virtualenvs/ms1.10/local/lib/python2.7/site-packages/django/core/management/base.py", line 342, in execute self.check() File "/home/user/.virtualenvs/ms1.10/local/lib/python2.7/site-packages/django/core/management/base.py", line 374, in check include_deployment_checks=include_deployment_checks, File "/home/user/.virtualenvs/ms1.10/local/lib/python2.7/site-packages/django/core/management/commands/migrate.py", line 62, in _run_checks issues.extend(super(Command, self)._run_checks(**kwargs)) File "/home/user/.virtualenvs/ms1.10/local/lib/python2.7/site-packages/django/core/management/base.py", line 361, in _run_checks return checks.run_checks(**kwargs) File "/home/user/.virtualenvs/ms1.10/local/lib/python2.7/site-packages/django/core/checks/registry.py", line … -
Postgres select function in Django annotation
I have old database and need custom select. in sql i can use: SELECT x(geometry) FROM table but I dont know how to force x() function in django select. -
django tastypie patch gives me a "500" error
it showing the error "error_message": "invalid literal for int() with base 10: ''" I am getting this error for patch request to a user resource. my user model is class User(AbstractBaseUser): VIA_FACEBOOK = 1 VIA_GOOGLE = 2 SIGN_IN_TYPES = ( (VIA_FACEBOOK,'facebook'), (VIA_GOOGLE,'google') ) MALE = 1 FEMALE = 0 GENDERA_TYPES = ( (FEMALE,'female'), (MALE,'male') ) SINGLE_ACCOUNT_USER = 0 JOINT_ACCOUNT_USER = 1 USER_TYPES = ( (SINGLE_ACCOUNT_USER,'single_accout_user'), (JOINT_ACCOUNT_USER,'joint_accout_user') ) first_name = models.CharField(blank = True, max_length=50) middle_name = models.CharField(blank=True, max_length=50,null=True ) last_name = models.CharField(blank=True, max_length=50,null=True) email = models.EmailField(blank=False,unique=True,max_length=100) sign_in_via = models.SmallIntegerField(choices=SIGN_IN_TYPES, default=0) mobile = models.CharField(blank=True, max_length=10,null=True ) dob = models.DateField(blank=True, null=True) profile_pic_url = models.CharField(blank=True,max_length=300,null=True) background_pic_url = models.CharField(blank=True,max_length=300,null=True) gender = models.SmallIntegerField(blank=True,choices=GENDERA_TYPES,null=True) user_type = models.SmallIntegerField(blank=False,choices=USER_TYPES,default=0) details = models.CharField(blank=True,max_length=500,null=True) created_on = models.DateTimeField(auto_now=True) slug = models.SlugField(default='') USERNAME_FIELD = 'email' ` MY user resource script is : class UserResource(ModelResource): class Meta: queryset = User.objects.all() resource_name = 'user' list_allowed_methods = ['get', 'post', 'patch', 'put','delete'] authorization = Authorization() include_resource_uri = True always_return_data = True authentication = Authentication() filtering = { 'id': ALL, 'email': ALL, 'user_type': ALL, 'mobile': ALL, 'created_at': ALL, } excludes = ['created_on','password','last_login','sign_in_via'] GET and POST are working fine, but PATCH and PUT methods are not working. i am making a request usind Postman so, for an PATCH request … -
PyCharm on Windows: 'django-admin' is not recognized as an internal or external command
When I try to install Django, PyCharm's Console shows me: (my_env) C:\projects\app\web>pip install django==1.8.6 You are using pip version 7.1.0, however version 9.0.1 is available. You should consider upgrading via the 'python -m pip install --upgrade pip' command. Collecting django==1.8.6 Using cached Django-1.8.6-py2.py3-none-any.whl Installing collected packages: django Exception: Traceback (most recent call last): File "C:\projects\app\web\my_env\lib\site-packages\pip\basecommand.py", line 223, in main status = self.run(options, args) File "C:\projects\app\web\my_env\lib\site-packages\pip\commands\install.py", line 299, in run root=options.root_path, File "C:\projects\app\web\my_env\lib\site-packages\pip\req\req_set.py", line 646, in install **kwargs File "C:\projects\app\web\my_env\lib\site-packages\pip\req\req_install.py", line 813, in install self.move_wheel_files(self.source_dir, root=root) File "C:\projects\app\web\my_env\lib\site-packages\pip\req\req_install.py", line 1008, in move_wheel_files isolated=self.isolated, File "C:\projects\app\web\my_env\lib\site-packages\pip\wheel.py", line 479, in move_wheel_files maker.make_multiple(['%s = %s' % kv for kv in console.items()]) File "C:\projects\app\web\my_env\lib\site-packages\pip\_vendor\distlib\scripts.py", line 334, in make_multiple filenames.extend(self.make(specification, options)) File "C:\projects\app\web\my_env\lib\site-packages\pip\_vendor\distlib\scripts.py", line 323, in make self._make_script(entry, filenames, options=options) File "C:\projects\app\web\my_env\lib\site-packages\pip\_vendor\distlib\scripts.py", line 227, in _make_script self._write_script(scriptnames, shebang, script, filenames, ext) File "C:\projects\app\web\my_env\lib\site-packages\pip\_vendor\distlib\scripts.py", line 163, in _write_script launcher = self._get_launcher('t') File "C:\projects\app\web\my_env\lib\site-packages\pip\_vendor\distlib\scripts.py", line 302, in _get_launcher result = finder(distlib_package).find(name).bytes File "C:\projects\app\web\my_env\lib\site-packages\pip\_vendor\distlib\resources.py", line 297, in finder raise DistlibException('Unable to locate finder for %r' % package) pip._vendor.distlib.DistlibException: Unable to locate finder for 'pip._vendor.distlib' But when I run pip freeze, it shows me: (my_env) C:\projects\app\web>pip freeze You are using pip version 7.1.0, however version 9.0.1 is available. You should … -
Python code in Django not recompiling in daemon mode with Apache/mod_wsgi
I am running a Django application using Apache2 with mod_wsgi in daemon mode: WSGIDaemonProcess my_app_process WSGIScriptAlias /my_app /var/www/my_app/wsgi.py process-group=my_app_process WSGIScriptReloading On Whenever I make changes to my Python code on server (I know this is highly discouraged, but I'm only using it for debugging) I keep having trouble with recompiling the code, but only in subdirectories. Python files in the root directory of the application (i.e. settings.py) get recompiled nicely, but not the ones located in subdirectories (i.e. views.py of some app). The application directory is owned by the www-data user and the user has sufficient privileges (tested with 777). Restarting the Apache or touching the wsgi file only results in recompiling of the Python files in root directory of the application. -
Django views detect if client uses webgl compatible browser
Is there any option to detect in the view function if the browser from which the user is coming is webGL compatible or not? -
What is the correct way of doing Django imports ?
I would like to understand if the there is a correct and accepted way of handling imports in Django? I use following patterns > # import views from Django app called xxx to urls.py in the same app from . import views What I see been used in many tutorials and blogs > # import views from Django app called xxx to urls.py in the same app from xxx import views Similarly I use > # import YYY and XXX from xxx.models to xxx.serializers.py from .models import YYY, XXX What I see been used for example in Django-Rest-Framework tutorial is > # import YYY and XXX from xxx.models to xxx.serializers.py from xxx.models import XXX, YYY Doing imports in the way shown in tutorials does not work in my Django apps. Am I doing something wrong? I picked my way from Django documentation. I am using Django 1.10 with Python3.5 -
Extends tag with Django
I'm trying to use extends tag in order to simplify my HTML files and mainly not write several time the same things. So I created a Base.html file and Home.html which are located in : Etat_civil |__Home |__templates |__Home.html |__BirthCertificate |__Identity |__templates |__Base.html This is my Base.html file : <!--DOCTYPE html --> <html> <head> {% load staticfiles %} <title> DatasystemsEC - Accueil </title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <link rel="stylesheet" type="text/css" href="{% static 'css/Base.css' %}"/> </head> <!-- #################### --> <!-- Upper navigation bar --> <!-- #################### --> <nav class="navbar navbar-inverse"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="http://www.datasystems.fr/"> DatasystemsEC </a> </div> <!-- Home tab --> <ul class="nav navbar-nav"> <li><a href="{% url "accueil" %}"> <span class="glyphicon glyphicon-home"></span> Accueil </a></li> <!-- Individual form tab --> <li class = "dropdown"> <a href = "accueil" class = "dropdown-toggle" data-toggle = "dropdown"> <span class="glyphicon glyphicon-baby-formula"></span> Fiches Individuelles <b class = "caret"></b> </a> <ul class = "dropdown-menu"> <li><a href = "{% url "home" %}"> Accueil des fiches individuelles </a></li> <li><a href = "{% url "form" %}"> Création des fiches individuelles </a></li> <li><a href = "{% url "searched" %}"> Consultation des fiches individuelles </a></li> <li><a … -
uWSGI and nginx serving static from Django
I've setup a django project to serve static with nginx and uses uwsgi also. While running in debug = True I can view a demo static file on the homepage and admin static is loading but when I set debug = False it fails to load static files. I've set the permissions for the folder to 666 but it didn't resolve the issue. Here's the settings in the settings file STATIC_URL = '/static/' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'kb/media') STATICFILES_DIRS = [os.path.join(BASE_DIR, 'kb/static/'),] nginx config file kb_nginx.conf # mysite_nginx.conf # the upstream component nginx needs to connect to upstream django { server unix:///home/ubuntu/kb/kb.sock; # for a file socket #server 127.0.0.1:8001; # for a web port socket (we'll use this first) } # configuration of the server server { # the port your site will be served on listen 8000; # the domain name it will serve for server_name kenyabuzz.nation.news; # substitute your machine's IP address or FQDN charset utf-8; # max upload size client_max_body_size 75M; # adjust to taste # Django media location /media { alias /home/ubuntu/kb/kb/media; # your Django project's media files - amend as required } location /static { alias /home/ubuntu/kb/kb/static; # your Django project's static files … -
How get individual fields from django model?
In my django models.py : class Agent1(models.Model): show_name = models.CharField(db_column='Show_Name', max_length=100,null=True) exhibiting_company_name = models.CharField(db_column='Exhibiting_Company_Name', max_length=100,null=True) # Field name made lowercase. company_website = models.CharField(db_column='Company_Website', max_length=100,null=True) # Field name made lowercase. company_generic_email = models.EmailField(db_column='Company_Generic_Email', max_length=100,null=True) # Field name made lowercase. class Agent2(models.Model): show_name = models.CharField(db_column='Show_Name', max_length=100,null=True) exhibiting_company_name = models.CharField(db_column='Exhibiting_Company_Name', max_length=100,null=True) # Field name made lowercase. company_website = models.CharField(db_column='Company_Website', max_length=100,null=True) # Field name made lowercase. company_generic_email = models.EmailField(db_column='Company_Generic_Email', max_length=100,null=True) # Field name made lowercase. Like this i have around 30+ models this are just a few fields i have over 20 fields & in my new_data.html file i have : <form method="post"action="">{% csrf_token %} {{ form.as_p}} <input type="submit" name="" value="Submit"> </form> How can i display only for e.g. show_name and exhibiting_company_name in my html template without creating a custom form in forms.py ? Is there any way to call my model fields individually in a <input> tag like this : <form action="demo_form.asp"> Show Name: <input type="text" name="sname"><br/> Company Name: <input type="text" name="cname"><br/> <input type="submit" value="Submit"> </form> ? -
__init__() got an unexpected keyword argument 'mimetype' for application/x-zip-compressed in django [on hold]
I am working on a function where i have to download tickets in zip folder, so i have written this code. tickets = Event_Ticket_Payment_Details.objects.all().filter(event_id = event_id).values('id', 'ticket_pdf', 'event_id__event_title') zip_subdir = tickets[0]['event_id__event_title'] zip_subdir = re.sub('\s', '-', zip_subdir) zip_filename = "%s.zip" % zip_subdir s = StringIO.StringIO() zf = zipfile.ZipFile(s, "w") for ticket in tickets: ticketPath = settings.MEDIA_ROOT+'/tickets_pdf/%s' %ticket['ticket_pdf'] fdir, fname = os.path.split(ticketPath) zip_path = os.path.join(zip_subdir, fname) zf.write(ticketPath, zip_path) zf.close() resp = HttpResponse(s.getvalue(), mimetype = "application/x-zip-compressed") resp['Content-Disposition'] = 'attachment; filename=%s' % zip_filename return resp I got this code from stackoverflow and i have changed it according to my requirements. It's only giving error after zf.close() line. -
Troubleshooting API timeout from Django+Celery in Docker Container
I have a micro-services architecture of let say 9 services, each one running in its own container. The services use a mix of technologies, but mainly Django, Celery (with a Redis Queue), a shared PostgreSQL database (in its own container), and some more specific services/libraries. The micro-services talk to each other through REST API. The problem is that, sometimes in a random way, some containers API doesn't respond anymore and get stuck. When I issue a curl request on their interface I get a timeout. At that moment, all the other containers answer well. There is two stucking containers. What I noticed is that both of the blocking containers use: Django django-rest-framework Celery django-celery An embedded Redis as a Celery broker An access to a PostgreSQL DB that stands in another container I can't figure out how to troubleshoot the problem since no relevant information is visible in the Services or Docker logs. The problem is that these API's are stuck only at random moments. To make it work again, I need to stop the blocking container, and start it again. I was wondering if it could be a python GIL problem, but I don't know how to check this … -
Is there a way to specify the database alias that is concerned by a RunPython operation in a Django migration?
I have a Django project that uses two databases. I defined a Database Router and everything works fine when running migrations, except for RunPython migration operations : in this case I have to "manually" check in the RunPython code function on which database alias the code is run to decide whether or not to apply the given operations. So far I have implemented a decorator that I use on every RunPython code function that checks whether or not to run the operation based on the current database alias. It works fine, but I was wondering if Django already provided a way to specify the database alias(es) concerned by a RunPython migration without having custom code. Is there such a way ? For information, here is the decorator : def run_for_db_aliases(database_aliases): def decorator(migration_function): def decorated(apps, schema_editor): if schema_editor.connection.alias not in database_aliases: return return migration_function(apps, schema_editor) return decorated return decorator This allows me to define code for RunPython migrations like this : @run_for_db_aliases(['default']) def forwards_func(apps, schema_editor): # Perform data operations on models that are stored in the 'default' database ... Is there a cleaner way to do this, like an option when instantiating a RunPython operation ? -
Django: Concurrent access to settings.py
I am not sure whether I have to care about concurrency, but I didn't find any documentation about it. I have some data stored at my settings.py like ip addresses and each user can take one or give one back. So I have read and write operations and I want that only one user read the file at the same moment. How could I handle this? And yes, I want to store the data at the settings.py. I found also the module django-concurrency. But I couldn't find anything at the documentation. -
django for permisosin ,add ,delete ,change
I have Post model and I want to allow user to add and change and delete global | post | Can add a post global | post | Can delete the post global | post | Can change post can someone help me ?? I try this in my views and its give me error. User.objects.get_or_create(username=username, is_staff=True) u = User.objects.get(username=user.username) permissions = Permission.objects.get(name='post_can_add_post') u.user_Permission.add(permissions) -
TypeError: node is null . Javascript library and functions is not working in mozilla after installing django-htmlmin
Some Javascript library/function is not working in mozilla after installing django-htmlmin but others browser its working fine.Please help,thanks in advance! Mozilla Firefox 50.1.0 django version 1.7 python 2.7 I Installed sudo pip install django-htmlmin pip install --upgrade beautifulsoup4 pip install --upgrade html5lib In setting I added below code for minify html--- MIDDLEWARE_CLASSES = ( 'htmlmin.middleware.HtmlMinifyMiddleware', 'htmlmin.middleware.MarkRequestMiddleware', ) HTML_MINIFY = True In browser console I am getting - TypeError: node is null . -
My Celery task is not running
Here is my tasks.py file: from celery.schedules impor @task(name='coupon.generate_reports') def update_monthly_coupons_reports(): # some code app.conf.beat_schedule = { # Executes every Monday morning at 7:30 a.m. 'add-every-morning': { 'task': 'coupon.generate_reports', 'schedule': crontab(hour=7, minute=30), }, } and CELERYBEAT_SCHEDULER = 'djcelery.schedulers.DatabaseScheduler' is in settings. But there is no result of task exectuting. Is there steps that I've missed? -
Env variable in Vagrant provision with Ansible and Django
I am using Django and trying to configure Vagrant. In my settings file, I access an environment variable like so: CERTIFICATE = get_env_setting('CERTIFICATE_FILEPATH') get_env_setting() function looks like this: def get_env_setting(setting): try: return os.environ[setting] except KeyError: error_msg = "Set the %s env variable" % setting raise ImproperlyConfigured(error_msg) And at the end of provisioning I run migrations with ansible like this: - name: run migrations shell: > executable=/bin/bash {{ venv_dir }}/bin/python {{ project_dir }}manage.py migrate This is where I get this exception: ImproperlyConfigured: Set the CERTIFICATE_FILEPATH env variable I tried to add this env variable like this: - name: add env variables lineinfile: dest={{ home_dir }}.profile line="export CERTIFICATE_FILEPATH='/path/'" regexp="^export CERTIFICATE_FILEPATH" It did add this env variable to ~/.profile but the error still occurred. How can I fix this? -
Django OneToOne Fields to user ProgrammingError
I tried to add a ManyToManyField to user using a OneToOneField relation first. Here is my code: ENTERPRISE_TYPE_CHOICES = ( ('a', "A"), ('b', "B"), ('c', "C"), ) class Enterprise(models.Model): et_type = models.CharField( max_length = 10, choices=ENTERPRISE_TYPE_CHOICES, default='a' ) name = models.TextField(max_length=100) number = models.TextField(max_length=7) def __str__(self): return "%s %s %s" % (self.et_type, self.name, self.number) class Secretaire(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) workshop = models.ManyToManyField(Enterprise) @receiver(post_save, sender=User) def create_user_secretaire(sender, instance, created, **kwargs): if created: Secretaire.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_secretaire(sender, instance, **kwargs): instance.profile.save() Then in the python manage.py shell I try : from django.contrib.auth.models import User u = User.objects.create(username="a", email="a@a.fr", password="a") And it throw the error : ProgrammingError: relation "helpdesk_secretaire" does not exist LINE 1: INSERT INTO "helpdesk_secretaire" ("user_id") VALUES (11) RE... (The User is still created but no can't acces to user.secretaire, it throws the same error) Do you have any clue about why I get this error?