Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django pass Python Object from view to Javascript script in template
This is a simple code created only to show the probem, obviusly the task that this simple code is trying to do can be done without Javascript, but I need to know how I can do this using Javascript, because In my real code I need it, and It cant't be done without Javascript (basically I create a dinamic 2D array with information from the view) in view.py in def play_game function ... players = Player.objects.all() context = { 'players' : players } return render(request,'play_game.html', context) in model.py class Player(models.Model): game = models.ForeignKey(Game, on_delete=models.CASCADE, blank=True, null=True) loose = models.IntegerField( default=0) win = models.IntegerField(default=0) name = models.CharField(max_length=9) In play_game.html <script> var players = "{{players}}"; for (player in players) { document.write(player.name); document.write(" Win:"+ player.win); document.write("Loose: " + player.loose); }; </script> -
django login required for the entire site not working
I am trying to use a code to force login if a user is not authenticated yet. I have tried too many codes and I could not get them working since most of them written in older versions of django. I am using django 1.10.3. I am not getting any errors when running the server, but I am not getting redirected to the login page too while I am not logged in. I am not even sure we can have both MIDDLEWARE AND MIDDLEWARE_ClASSES in the setting file. Any help would be appreciated. I also would like to have exceptions where I can make some of the views public that requires no login middleware.py: from builtins import hasattr, any from django.http import HttpResponseRedirect from django.conf import settings from re import compile from django.core.urlresolvers import reverse def get_login_url(): return reverse(settings.LOGIN_URL_NAME) def get_exempts(): exempts = [compile(get_login_url().lstrip('/'))] if hasattr(settings, 'LOGIN_EXEMPT_URLS'): exempts += [compile(expr) for expr in settings.LOGIN_EXEMPT_URLS] return exempts class LoginRequiredMiddleware(object): """ Middleware that requires a user to be authenticated to view any page other than reverse(LOGIN_URL_NAME). Exemptions to this requirement can optionally be specified in settings via a list of regular expressions in LOGIN_EXEMPT_URLS (which you can copy from your urls.py). Requires … -
django model formset update only
I want to use ModelFormset to update table data. Each row on picture contains one form with two fields, and one field in form required. I don't want to use empty form to create new object and can just remove it from rendering in template, and subclass save method to save only forms with initial data from queryset: class MyFormSet(BaseModelFormSet): def save(self, commit=True): if not commit: self.saved_forms = [] return self.save_existing_objects(commit) but empty form still need to be validated, and i got validation error on required field. How can i disable using/validating of "new object" form? -
How do you set a individual html meta description when redirected by login_required?
I use the decorator login_required. If I do a search via Google the link to the restricted page has the html meta description etc. from the login template. How do you set individual meta tags (like description) when the page is restricted by login_required? -
python error with eclipse
i try to do thins in eclipse python and i get this error !/usr/bin/python3 -- coding: utf-8 -- import os import collections def listAllFiles(dirName, ext): allfiles = [] for root, subdirs, files in os.walk(dirName): for filename in files: file_path = os.path.join(root, filename) if file_path.endswith(ext): if '.git' not in file_path: allfiles.append(file_path) return allfiles def clean(t): w = "" validChar = ["ا", "أ", "إ", "آ", "ء", "ئ", "ؤ", "ب", "ت", "ة", "ث", "ج", "ح", "خ", "د", "ذ", "ر", "ز", "س", "ش", "ص", "ض", "ط", "ظ", "ع", "غ", "ف", "ق", "ك", "ل", "م", "ن", "ه", "و", "ى", "ي"] for char in t: if char in validChar: w = w + char return w def extractFileWords(fn): fh = open(fn, 'r') fileWords = [] for line in fh: t = line.split() if len(t) > 0: fileWords.extend(t) fh.close() return fileWords def extraxtFilesWords(fl): allWords = [] for fn in fl: print(fn) fw = extractFileWords(fn) print(len(fw)) allWords.extend(fw) print("allWords", len(allWords)) if(len(allWords) > 1100000): break return allWords def createWordFrequenciesList(filesWords, resFile, statFile, rankFile): runSize = 1000000 statfh = open(statFile, "w") statfh.write("mean \t median \t mode\n") rankfh = open(rankFile, "w") fn, fx = resFile.split('.') run = 1 wfs = {} tc = 0 for t in filesWords: w = clean(t) if(len(w) > … -
Can I use sendmail for Django's send_mail?
I am setting up a Django-based hobby site on a VPS, and I am confused with Django's email system configuration. My server is successfully sending me technical emails (e.g. from fail2ban) using sendmail. However all Django-related googling mentions postfix, e.g. in this other answer. I wonder: If I can use sendmail rather than postfix; How I can configure Django to use my server's mailing functionality. Any help is much appreciated. FWIW, I am on Ubuntu 16.04 and Django 1.10. -
Vaultier blank page
I followed the instruction from the official site. and I have stopped on the latest point , which is called "Verify the Installation" . In installation time I successfully solved some bags but now im confused. My problem is that when I start vaultier, I get blank page. Im not sure but it's probably problem with my nginx configuration and Vaultier. There is my nginx config: server { server_name www.example.com; listen *:80; client_max_body_size 10M; access_log /opt/vaultier/logs/nginx-access.log; error_log /opt/vaultier/logs/nginx-error.log; location / { include uwsgi_params; uwsgi_pass unix:/run/uwsgi/app/vaultier/socket; } location /static { alias /opt/vaultier/venv/lib/python2.7/site-packages/vaultier/vaultier/static/; } location /media { alias /opt/vaultier/venv/lib/python2.7/site-packages/vaultier/vaultier/media/; } } And there is my vaultier_conf.py Vaultier configuration file """ from vaultier.settings.prod import * import os RAVEN_CONFIG = { 'dsn': '' } ALLOWED_HOSTS = [ '*', 'www.example.com', ] VAULTIER.update({ 'raven_key': '', 'registration_allow': False, 'allow_anonymous_usage_statistics': True, 'from_email': 'noreply@example.com', }) CONFIG_DIR = os.path.abspath(os.path.dirname(__file__)) MEDIA_ROOT = os.path.join(CONFIG_DIR, 'data') SECRET_KEY = 'c66wn2(tt!ab_bhznm9!mdp7krqz7der_)al!^(8v$+s3f1$wh' DATABASES = { 'default': { # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'. 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'vaultier', # Or path to database file if using sqlite3. # The following settings are not used with sqlite3: 'USER': 'vaultier', 'PASSWORD': 'wB5k1u8iz00Aun2rr3GZ', # Empty for localhost through domain sockets or '127.0.0.1' # for localhost through TCP. 'HOST': '127.0.0.1', … -
Django url that captures yyyy-mm-dd date
How do you capture a url that contains yyyy-mm-dd in Django. So like www.mydomain.com/2011-02-12. I tried url(r'^(?P\d{4}-\d{2}-\d{2})/$', views.index, name='index'), but server says page not found. -
Tastypie foreign key set null
I need to set foreign key to null while updating the object. Here is the model: class Task(models.Model): parent_milestone = models.ForeignKey("Milestone", null=True, blank=True) parent_task = models.ForeignKey("Task", null=True, blank=True) name = models.CharField(max_length=256) description = models.TextField(blank=True, null=True) deadline = models.DateTimeField(blank=True, null=True) priority = models.IntegerField(default=2) done = models.BooleanField(default=False) def __unicode__ (self): return self.name Here is the tastypie resource: class TaskResource(ModelResource): subtasks = fields.ToManyField('self', 'task_set', full=True, readonly=True) parent_milestone = fields.ToOneField(MilestoneResource, 'parent_milestone', null=True, full=False) parent_task = fields.ToOneField('self', 'parent_task', null=True, full=False) ... def obj_update(self, bundle, **kwargs): bundle = super(TaskResource, self).obj_update(bundle, **kwargs) bundle.data['name'] = "test" bundle.data['parent_milestone'] = None <-- error here return self.obj_create(bundle, **kwargs) While updating a see the the name is updated (any updated object getting the name "test"). But when updating the parent_milestone I get this error: "'NoneType' object has no attribute 'parent_milestone'" Any help please? -
using GET variables with django
I'm just trying to get a minimum working example of GET variable usage in django. Apologies, I'm very very new to django. At the moment, urls.py looks like: urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^test/', views.engage), ] views.py: def engage(request): return(request.GET) I'm trying to access an integer variable at domain.com/test/&n=10 but at this stage I keep getting Exception Type: AttributeError Exception Value: This QueryDict instance is immutable I've been trying to figure this out for about 2 days now. I've searched pretty widely, but I just don't seem to be getting anywhere. I don't need the answer on a silver platter; links to tutorials etc would be equally appreciated. I feel like there's something pretty core that I'm missing. Thanks. -
container command migrate does not create all tables
option_settings: "aws:elasticbeanstalk:application:environment": DJANGO_SETTINGS_MODULE: "myApp.settings" "PYTHONPATH": "/opt/python/current/app/myApp:$PYTHONPATH" "ALLOWED_HOSTS": ".elasticbeanstalk.com" "aws:elasticbeanstalk:container:python": WSGIPath: myApp/myApp/wsgi.py NumProcesses: 3 NumThreads: 20 "aws:elasticbeanstalk:container:python:staticfiles": "/static/": "www/static/" container_commands: 01_migrate: command: "source /opt/python/run/venv/bin/activate && python myApp/manage.py migrate --noinput" leader_only: true 02_createsu: command: "source /opt/python/run/venv/bin/activate && python myApp/manage.py createsu" leader_only: true 03_collectstatic: command: "source /opt/python/run/venv/bin/activate && python myApp/manage.py collectstatic --noinput" I deployed my django app with the help of aws elastic beanstalk. However, the migrate command does not create all necessary tables. So, I checked the logs and I realized the following warning; WARNINGS: ?: (mysql.W002) MySQL Strict Mode is not set for database connection 'default' HINT: MySQL's Strict Mode fixes many data integrity problems in MySQL, such as data truncation upon insertion, by escalating warnings into errors. It is strongly recommended you activate it. I tried to set it on my setting.py like; DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': os.environ['RDS_DB_NAME'], 'USER': os.environ['RDS_USERNAME'], 'PASSWORD': os.environ['RDS_PASSWORD'], 'HOST': os.environ['RDS_HOSTNAME'], 'PORT': os.environ['RDS_PORT'], 'OPTIONS': { 'init_command': "SET sql_mode='STRICT_ALL_TABLES'" } } } However, it didn't work and I really stucked at this point. -
Lightweight message queue to use with Celery 4.0
I'm currently using Celery 3.1 in a Django project on Python 2.7. So far, we were using the Django ORM as a broker for development and staging environments. That was convenient, because you could pretty much just check out the sources, install the dependencies, run the migrations and celery worker would just work out of the box. I'm thinking about how to set that up after upgrading to Celery 4.x due to the Django ORM broker having been removed. Are there any message queues that don't require any local setup (or can be pip-installed) and separate launching? -
Do I make the is_superuser accessble to my api in django?
I'm working on a project using django and angular and I need to make some pages accessible only to superusers. I've read somewhere that it isn't advisable to make this available to clients. If so is there any way to make some pages visible only to superusers? I'm new at this so forgive me if the question sound naive. Thank you -
Django: Same code base, same database, but slightly different templates and static files
What method/framework should I use to run multiple websites that share 100% of the code base? The sites should all share a single database, but have slightly different templates, slightly different static files and completely different media files. I am thinking of a method where I can have base templates and base static files that can be overridden with site specific templates/static files. What method can I use to accomplish the task of running multiple sites in this way? Also important: What is a reasonable directory structure? -
Django - Submit multiple forms with one submit button
I'm trying to create a check in page that lists all of the people that have signed up. Each person has an input box that submits the number of hours they were at the event. I want it so that the same form is submitted multiple times for every person; I don't want to have a submit button for every person because there will be several people and it'll be tedious. I'm using a for loop {% for signups in signup %} to loop through the queryset for the people who are signed up. Here's a screenshot to illustrate: In the backend, I want it to save the number of hours to the row in the queryset with the matching name. -
Authentication failure using Zoho smtp with Django
I am trying to send email using my django app. But after setting Zoho account and adding necessary lines in settings.py I am still not able to send email and it keep giving SMTPAuthenticationError (535, b'Authentication Failed'). #settings.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.zoho.com' EMAIL_HOST_USER = 'administrator@technovate-iiitnr.org' EMAIL_HOST_PASSWORD = 'mypass' EMAIL_PORT = 587 EMAIL_USE_TLS = True #views.py html = render_to_string('email/code_email.html',{'code':code}) send_mail('Your Code', 'Hello', 'administrator@technovate-iiitnr.org', ['example@gmail.com'], html_message=html ) return render(request,'index.html') enter image description here -
TypeError: 'str' object is not callable in Django 1.10 Admin change_form.html {{ original|truncatewords:"18" }}
I've had this a couple of times and not been able to debug it. Last time I regressed code to my last checkin to avoid it but it remains a mystery. Situation occurs when I use the standard admin app to view/edit my custom objects. I can see the objects listed in the view (in my case http://127.0.0.1:8000/admin/athletes/totalsandstats/ where athletes is my app name, and TotalsAndStats is a model defined within athletes/models.py). When I click on one of the objects to try and view the details, I get the above exception. Django Admin is trying to render the URL http://127.0.0.1:8000/admin/athletes/totalsandstats/2/change/ using the template /usr/local/lib/python3.4/site-packages/django/contrib/admin/templates/admin/change_form.html The error page states that the exception occurred at line 21 in the template, which is this: &rsaquo; {% if add %}{% blocktrans with name=opts.verbose_name %}Add {{ name }}{% endblocktrans %}{% else %}{{ original|truncatewords:"18" }}{% endif %} I see that {{ original|truncatewords:"18" }} is highlighted in red so I assume that "original" is not defined correctly. But I don't know what is the purpose of original, or how it relates to my model. I suspect there must be some mismatch between my model and the way I have defined the corresponding admin model, but I can't … -
get REST values in python script
i have a rest api with this structure : [ { "id": 1, "user_iput": "ماهو سعر الايفون٧؟", "chatbot_response": "سعر الايفون حالياً ٣٢٩٩ ريال" }, { "id": 2, "user_iput": "باي", "chatbot_response": "response defult text" } ] Now in a python script i want to get the value of "user_iput" in the last object, then do some calculation using its value and then the then the "chatbot_response" value will be updated using lets say B var for example. this is my python script: import requests import json def get_user_input(): api = 'http://127.0.0.1:8000/chat/api/' r = requests.get(api) return str(r.json()) def update_chat_responce(Output): api = 'http://127.0.0.1:8000/chat/api/' data = json.dumps(Output) r = requests.put(api, data=data) #-----------------------------------------------# def run_conversation_male(): H = get_user_input() New_H= ' '.join(PreProcess_text(H)) update_chat_responce(New_H) any ideas?..... Thank you, -
How can I make the development server in Python Django be on the internet?
I want to make the development server in Django be on the internet while running Windows 10. How can I do this? -
Creating web interface for ffmpeg
How can i create web form with a list of user defined variables (ffmpeg filters and params) using Django or Flask? Specifically i want to pass text input for ffmpeg drawtext filter and output format. -
upload image using own model Django
I got simple form. I want to save image and than render it in template. Problem is that image is never uploaded in DB(checked mysql DB). I don't get any errors.Form is submitted(valid), all other values in form are stored and i can render them in template.Only picture is problem.I have all permissions for write and read for folder where i want to upload. settings.py import os gettext = lambda s: s DATA_DIR = os.path.dirname(os.path.dirname(__file__)) """ Django settings for bloger project. Generated by 'django-admin startproject' using Django 1.8.17. For more information on this file, see https://docs.djangoproject.com/en/1.8/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.8/ref/settings/ """ # Build paths inside the project like this: os.path.join(BASE_DIR, ...) import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '_g$(y(@55v1i@a22$tgnpermt78(w!+(*pfei3483+&h)o1@xb' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition ROOT_URLCONF = 'bloger.urls' WSGI_APPLICATION = 'bloger.wsgi.application' # Database # https://docs.djangoproject.com/en/1.8/ref/settings/#databases # Internationalization # https://docs.djangoproject.com/en/1.8/topics/i18n/ LANGUAGE_CODE = 'en' TIME_ZONE = 'Europe/Ljubljana' USE_I18N = True USE_L10N = True USE_TZ = True # Static files … -
Import sql file into Django/Wagtail
I am working on a Django/Wagtail project with several contributors on Github. Recently, the db was switched to Postgres. I was able to successfully create a new Postgres db and migrate. I was also given an .sql file to import to update the data. The simple question is, how does one do this? I have viewed other posts, but since I recently migrated from sqlite3 to Postgres, I want to make sure I am not missing anything. -
Django Admin Custom Select box as per user in Admin
I have a model, which has User as Foreign Key. When I am viewing in the admin after login , showing all the user. I want to control it as per the user logged in the list should be displayed. How can I achieve this so that if user1 login I can see different list and if user2 logs in different list. -
Using Django to store session variable, but session variable not appearing in chrome://settings/cookies
I have tried to set session variables with both simply request.session['test'] = id and from django.contrib.sessions.backends.db import SessionStore s = SessionStore() s['test'] = id s.save() Of course I've enabled the appropriate middleware. 'django.contrib.sessions.middleware.SessionMiddleware' I feel I must be setting the session variable correctly because when I print things like print request.session['test'] and print s.session_key I get the output I would expect. What I don't expect to see is that when going to chrome://settings/cookies I don't see the cookies set with the session variables anywhere. Am I misunderstanding how this works? -
How to access related OneTOOneFIeld with a recursive model?
I got a model that is OneToOneField related to a recursive model, class A(models.Model): myfield = models.CharField(max_length=32) as = models.ManyToManyField('self', blank=True) class B(models.Model): a = models.OneToOneField(A) How do I I get the first 'myfield' in A's 'as' from a B's 'a'? So I tried and gone as far as a.a.as but can't call methods like firt().