Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django-easy-pdf - First Page without header and Footer
I've a Django-Rest-Framework project and I'm using django-easy-pdf , I read all documentation, but I didn't find information I need. Is possible to Hide Header and Footer on First Page? Is possible to create a table of contents ? Thanks -
Django form: can't access help_text from Django template
Using Django 1.10. From the docs, it seems that I should be able to access help_text from the template but I can't. class StudentForm(ModelForm): class Meta: model = Student fields = ['name', 'age'] help_text = { 'age': "enter your age in years and months", } In the template, the following prints nothing: {%for field in form %} {% if field.help_text %} <p class="help">Here{{ field.help_text|safe }}</p> {% endif %} {% endfor %} -
Append json data and refresh django template automatically
I receive json files to my django website when some asyncronous tasks are finished with celery. When I get this json files I append this information to the database with a function in a view (every time I refresh the page). And I also show an HTML table with this data. I want to append json data automatically when it is available (without refreshing the page) and I also want to refresh the HTML table automatically (without refreshing the page). Any Ideas?? Thanks, -
mod_wsgi Failed to parse WSGI script file | Exception occurred processing WSGI script | Unable to import 'site' module
I am using httpd with mod_wsgi with httpd on a centos 6.9 machine here are relevant files, I am trying to deploy django on an apache 2.15 version, triend to google a lot but couldnot solve the issue, any help would be appreciated django.conf WSGIPythonHome /home/pbadmin/venv/bin/python WSGIPythonPath /home/pbadmin/venv/lib/python2.7/site-packages <VirtualHost *:8888> ServerAdmin root@localhost ServerName 10.0.48.40 DocumentRoot /var/www/PBpy WSGIScriptAlias / /var/www/PBpy/PBpy/wsgi.py WSGIDaemonProcess PBpy python-path=/home/pbadmin/venv/lib/python2.7/site-packages ErrorLog "/home/pbadmin/pylogs" <Directory "/var/www/PBpy"> Order deny,allow Allow from all </Directory> </VirtualHost> wsgi.py import os import sys #sys.path.append('/var/www/PBpy') from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "PBpy.settings") application = get_wsgi_application() error log [Thu Jun 01 12:27:24 2017] [error] [client 10.0.32.94] mod_wsgi (pid=6148): Target WSGI script '/home/pbadmin/PBpy/apache/django.wsgi' cannot b$ [Thu Jun 01 12:27:24 2017] [error] [client 10.0.32.94] mod_wsgi (pid=6148): Exception occurred processing WSGI script '/home/pbadmin/PBpy/apach$ [Thu Jun 01 12:27:24 2017] [error] [client 10.0.32.94] Traceback (most recent call last): [Thu Jun 01 12:27:24 2017] [error] [client 10.0.32.94] File "/home/pbadmin/PBpy/apache/django.wsgi", line 10, in <module> [Thu Jun 01 12:27:24 2017] [error] [client 10.0.32.94] import django.core.handlers.wsgi [Thu Jun 01 12:27:24 2017] [error] [client 10.0.32.94] File "/home/pbadmin/venv/lib/python2.7/site-packages/django/__init__.py", line 3, in < -
Programming Error : relation does not exist
ProgrammingError at /profile relation "mtsauth_userinfo" does not exist LINE 1: ...fo"."affliation", "mtsauth_userinfo"."phone" FROM "mtsauth_u... ^ Request Method: GET Request URL: http://198.199.118.164/profile Django Version: 1.10.6 Exception Type: ProgrammingError Exception Value: relation "mtsauth_userinfo" does not exist LINE 1: ...fo"."affliation", "mtsauth_userinfo"."phone" FROM "mtsauth_u... ^ Exception Location: /usr/local/lib/python2.7/dist-packages/django/db/backends/utils.py in execute, line 64 Python Executable: /usr/bin/python Python Version: 2.7.12 Python Path: ['/home/django/django_project', '/home/django/django_project', '/usr/bin', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-x86_64-linux-gnu', '/usr/lib/python2.7/lib-tk', '/usr/lib/python2.7/lib-old', '/usr/lib/python2.7/lib-dynload', '/usr/local/lib/python2.7/dist-packages', I was clueless about this error. Dont know in which order makemigrations and migrate should be run for my project with postgresql in digitalocean. So far I've been deleting migrations files and running those commands but not luck. Is there anything which i need to know about makemigrations and migrate command on how they be run. -
How to replace memswap_limit in docker compose 3?
I have memswap_limit in my docker-compose file (version 2) and I want to change my docker-compose file on version 3. But I don't found how to replace memswap_limit. I saw advices like "To configure resource constraints. This replaces the older resource constraint options in Compose files prior to version 3 (cpu_shares, cpu_quota, cpuset, mem_limit, memswap_limit)." My docker-compose.yml file (version 2) db: image: postgres:alpine mem_limit: 512m memswap_limit: 512m -
Save pillow objects to S3 with django_storages
I want to save in S3 from Amazon an image that I resize with Pillow. That image is uploaded by the user and I will upload it once resized. That is, it does not exist in S3. Currently I'm doing it as follows: Being a list of Pillow objects def upload_s3(files): for f in files: print(f) path = default_storage.save('/test/cualquiersa/') f.save(path, "png") -
onClick HTML table cell save into django database
I have a table where you onClick it'll get the column and cell value in e.g: {"name" : Clark} Now how can I put the output directly into a form and save into database just by clicking at the same table cell without requiring a button or displaying field. The field in the HTML is just for testing, would later hide it. Any helps is much appreciated Here's my code model.py class OnClickFormSave(models.Model): data = models.CharField(max_length=100) def __str__(self): return self.data form.py class OnClickFormSaveForm(forms.ModelForm): class Meta: model = OnClickFormSave fields = ['data'] view.py def formsave_view(request): form = OnClickFormSaveForm(request.POST or None, request.FILES or None) if form.is_valid(): instance = form.save(commit=False) instance.save() return HttpResponseRedirect('/form') return render(request, 'onClickSave.html', {'form': form}) HTML <form method="post" enctype="multipart/form-data">{% csrf_token %} {{ form.data }} <input type="submit" value="Save Changes" /> </form> <table align="center" id="tableID" border="1" style="cursor: pointer;"> <thead> <tr> <th id="name">name</th> <th id="age">age</th> <th id="ID">ID</th> </tr> </thead> <tbody> <tr> <td>Clark</td> <td>29</td> <td>1</td> </tr> <tr> <td >Bruce</td> <td>30</td> <td>2</td> </tr> </tbody> </table> Javascript $('table tbody tr td').on("click", getColumnID); function getColumnID() { var $td = $(this), $th = $td.closest('table').find('th').eq($td.index()); var head = $th.attr("id"); $row = ($(this).text()); var table = $row; var cell = `{"${head}" : ${table}}`; console.log(cell); } -
Despite specifying the IAM role, Docker container can not access the Cloud watch log
First, I use the server environment: sever: django + nginx + uwsgi cloud: docker + AWS ECS logging: AWS CloudWatch log service + watchtower third party app I want to connect the credentials to the docker container. Because the watchtower needs permission to access the clooud watch log. So I applied the IAM Role to the task definitions in the same way as the http://www.tothenew.com/blog/attach-iam-role-to-an-aws-elastic-container-service-task/ link. The role of IAM was set as follows. AmazonEC2ContainerServiceFullAccess CloudWatchLogsFullAccess However, If I command curl 169.254.170.2$AWS_CONTAINER_CREDENTIALS_RELATIVE_URI, server returns 404 page not found error. And when I connect to the application, 502 error occurs. Do you know why? -
requirejs + django_select2
I've to tell that I'm not a JS expert, and I've none arround me :( I've already adapted some scripts, but I'm a pretty old school dev :) I'm building a wagtail / django app using requirejs as js assets combiner. I'm using it because I've ever been in a kind of JS dependencies hell, where nothing works because of multiple versions of same libs loaded, from different django apps... I've installed the django_select2 application, and I'm trying to adapt the django_select2.js asset. I've loaded select2 through bower, and I've updaetd my config.js: "shim": { select2: { deps: ["jquery"], exports: "$.fn.select2" } }, paths: { ... select2: "select2/dist/js/select2" } Then I'm trying to adapt the django_select2.js: require(['jquery', 'select2'], function ($, select2) { return (function ($) { var init = function ($element, options) { $element.select2(options); }; var initHeavy = function ($element, options) { var settings = $.extend({ ajax: { data: function (params) { var result = { term: params.term, page: params.page, field_id: $element.data('field_id') } var dependentFields = $element.data('select2-dependent-fields') if (dependentFields) { dependentFields = dependentFields.trim().split(/\s+/) $.each(dependentFields, function (i, dependentField) { result[dependentField] = $('[name=' + dependentField + ']', $element.closest('form')).val() }) } return result }, processResults: function (data, page) { return { results: data.results, … -
how to submit data to asp web page from using python and retrieve result-data after submitting the data
like there is static html page which redirects to an asp page after submitting the data . so i want to submit data using python to static page and get result back from asp page using python. and I am using python 3.5 -
How to create users in Django's backend database when using Vue.js and Auth0 for frontend authentication
I am trying to use Vue.js as a frontend, and Django as the backend for an SPA. In the frontend, I am leveraging Auth0 for user authentication and I want to send the id_token obtained from user registration/creation from Auth0 to the backend to create specific user profiles in real-time. Previously, I was using the following code to enable profile creation once a user is created: # Whenever a User account is created, it creates a profile for it too. def create_profile(sender, **kwargs): user = kwargs["instance"] if kwargs["created"]: user_profile = UserProfile(user=user) user_profile.save() post_save.connect(create_profile, sender=User) def __str__(self): return self.user.username I am fairly new to Vue.js and Javascript. Although Vue.js is a breeze to use, but I can't seem to figure out how to replicate similar functionality in Vue.js with Auth0. Any help/guidance/pointers in the right direction are appreciated. Thanks. -
Is it possible to create objects in loop without forms in Django?
I wanna create objects when for example push button in some webpage. So i have to make this loop in views.py or on webpage? -
how to debug Open-edx platform in web browser?
I would like to debug a course website which is created by Open-edx platform. But I am getting the problem in debugging. So please Help. -
elif condition in djnago view
I'm having view function which filters object and that filtered object does not exist in the database it adds the object to DB. and I'm getting data from a template using ajax post request. #view.py elif Projectwiseusersetup.objects.filter(userid = user,project_id = pid,db_profileid=db,setasdefaultproject=False) and chkbox==True: print "FtoT" is there anything wrong with above code? user,pid,db,chkbox }---- i'm getting from ajax post request, userid, project_id, db_profileid, setasdefaultproject }----- model fields here im, as i said above, checking with the database, this condition is not working for me. Help Me. -
Redirecting to new Django url after successful Ajax function execution?
I have one ajax function, which is doing request to check whether user input username is valid or not. For that i wrote one ajax function and created one view to check the validity. The view check the validity and return a JSON response. $.ajax({ url: 'some/url', data : {'username' : 'username'}, dataType: 'json', success: function (data) { if (data.results == "faile"){alert('Username not available')} }, complete : function(){ location.href = "some/new/url" + with json_data } }) }; If the username is taken, it ask the user to input again and if it's available, a new page will be loaded, and the datatype from the server will be a JSON data with multiple values. How can i load the new page with JSON data as a parameter. I used location.href but how can i put json as a parameter? -
Django how to implement a unread notification count system?
I am using django-channels (websocket) to create a chat room system. When user is on room-list page, he would see a badge beside the room name which shows number of new notifs since he entered room last time (a user can be a member of multiple rooms). Also if a new notification comes when user is still on room-list page, the corresponding bage should +1. So my question is, do I need to make new tables for this or it can be done with session+websocket. I have a message table already. -
Deploying SSL on Ubuntu for Django
I have an application which is created in python django. I must deploy it on the server with ssl. I have certificate files which are given by our network admin. But there is no .key file. I have.ca-bundle.crt.pem files. How can I configure the apache server or get key file from these files? -
Create A Sentiment Analysis Web App [on hold]
I'm building a web app that will scrap data from Twitter api and news webites, analyse sentiments for the keyword chosed by the "client" then output the results ( For now I just want to output a number between 0 and 1 ) Each user should be able to save their keywords. I know it's a lot of work but I just start learning and I'm tryin to figure it out wich tools should I use and do no waste time learning useless stuff. Here's what I have so far: Windows 7 32bit / 4 Gb Ram Python 3.6 + Pycharm Community Text Analysis API (Indico.io) Shared Hosting + cPanel (?!) Twitter API Heroku Account + CLI PostgreSQL 9.6 Git 2.8 Python Libraries: Pip - SetupTools - VirtualEnv - Tweepi I have no idea wich framework should I use to build the front end ( Django/Flask/etc..) and also how to build the app locally then deploy to heroku. Actually, I just know how to request an API call and output the result on the console so please be kind. Thanks! -
Django nested serializer "This field may not be null" while allow_null=Ture
I've been struggling with this problem. I am not sure what I'm missing. Please let me know if you have any suggestions... views.py: class DealAdminViewSet(viewsets.ModelViewSet): queryset = Deal.objects.all() serializer_class = CreateDealSerializer def create(self, request, format=None): data = { ... } serializer = CreateDealSerializer(data=deal) print serializer co_manager_array = [] if serializer.is_valid(): serializer.save() return Response(status=status.HTTP_201_CREATED) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) serializer.py: class CreateDealSerializer(serializers.Serializer): co_manager = serializers.PrimaryKeyRelatedField(allow_null=True, many=True, queryset=BookRunner.objects.all(), required=False) -
i want to make an LMS using edX.how can i install edX and its requirements?-python-django
Please suggest a documentation to integrate this application.I tried edX documentation.But i didn't get how to install requirements file. -
Django - Heroku - committing a change
I've been asked to make some changes to a Django app on Heroku previously managed by someone who is no longer available. I've not used Heroku before so I am hoping this is a really easy question. I cloned the app using heroku git:clone -a myapp I changed the base.html file. I literally removed a few lines of HTML. I then ran git add . git commit -m "Some helpful message" git push heroku master And I get this error traceback: Counting objects: 6, done. Delta compression using up to 4 threads. Compressing objects: 100% (5/5), done. Writing objects: 100% (6/6), 497 bytes | 0 bytes/s, done. Total 6 (delta 4), reused 0 (delta 0) remote: Compressing source files... done. remote: Building source: remote: remote: -----> Python app detected remote: -----> Running pre-compile hook remote: -----> Noticed django-wkhtmltopdf, bootstrapping wkhtmltopdf. remote: -----> No runtime.txt provided; assuming python-2.7.3. remote: -----> Using Python runtime (python-2.7.3) remote: -----> Noticed pylibmc. Bootstrapping libmemcached. remote: -----> Installing dependencies using Pip (1.2.1) remote: ERROR:root:code for hash md5 was not found. remote: Traceback (most recent call last): remote: File "/app/.heroku/python/lib/python2.7/hashlib.py", line 139, in <module> remote: globals()[__func_name] = __get_hash(__func_name) remote: File "/app/.heroku/python/lib/python2.7/hashlib.py", line 91, in __get_builtin_constructor remote: raise … -
send_mail not working in django
I wrote this code settings.py EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' EMAIL_HOST='smtp.gmail.com' EMAIL_PORT=587 EMAIL_HOST_USER = 'myemailhere@gmail.com' EMAIL_HOST_PASSWORD = '**********' DEFAULT_FROM_EMAIL = 'myemailhere@gmail.com' EMAIL_USE_TLS = True views.py def email(request): if request.method == 'GET': form = ContactForm() else: form = ContactForm(request.POST) if form.is_valid(): subject = form.cleaned_data['subject'] from_email = form.cleaned_data['from_email'] message = form.cleaned_data['message'] try: send_mail(subject, message, from_email ['myemailhere@gmail.com']) except BadHeaderError: return HttpResponse('Invalid header found.') return redirect('success') return render(request, "email.html", {'form': form}) def success(request): email = EmailMessage('Hello', 'how are you?', to=['myemailhere@gmail.com']) email.send() send_mail('Test mail', 'This is a test', 'myemailhere@gmail.com' ['myemailhere@gmail.com'], fail_silently=False) return HttpResponse('Success! Thank you for your message.') In success(request), I added a bit of redundant code to try sending mail in a different way just to check if other method is working or not. None of it is working. Can anyone please tell me why? I am a bit confused. Password is correct and i allowed less secured apps for gmail.This program is not throwing any error. Success page is called if email(request) tells that it has sent mail successfully. I am using django 1.11 and Python 2.7 Thankyou in advance :) -
python3.6.1&django 1.11.1&pycharm TemplateDoesNotExist
I tried to use render to show the html edited on my pycharm,but when I entered the addrress :127.0.0.1:8000/index/ the exception of TemplateDoesNotExist appeared TemplateDoesNotExist at /index/ index.html Request Method: GET Request URL: http://127.0.0.1:8000/index/ Django Version: 1.11.1 Exception Type: TemplateDoesNotExist Exception Value:index.html Exception Location: D:\python3.6.1\lib\site-packages\django\template\loader.py in get_template, line 25 Python Executable: D:\python3.6.1\python.exe Python Version: 3.6.1 Python Path: ['C:\\Users\\Administrator\\guest', 'D:\\python3.6.1\\python36.zip', 'D:\\python3.6.1\\DLLs', 'D:\\python3.6.1\\lib', 'D:\\python3.6.1', 'D:\\python3.6.1\\lib\\site-packages'] Server time: Fri, 2 Jun 2017 03:30:58 +0000TemplateDoesNotExist at /index/ settings.py as follows ROOT_URLCONF = 'guest.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, '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', ], }, }, ] views.py as follows from django.shortcuts import render # Create your views here. def index(request): return render(request,"index.html") my pycharm shown that:enter image description here I have tried some methods provided on stackoverflow but they do not work,does this exception caused by the wrong dirs? How can I deal with such situation -
Django:v1.9 migrate the exiting model ERROR
i am running web with Django 1.9 and have many models. (It may be to long) The old models: class Application_Delete_History(models.Model): name = models.CharField(max_length=128) delete_time = models.DateTimeField(null=True) status = models.BooleanField(default=True) class Review_Manager(models.Model): name = models.CharField(max_length=128) display_name = models.CharField(max_length=128) And i add many data in 2 models. And with my stupid action i created 2 new models: class Application_Status_Notification(models.Model): name = models.CharField(max_length=128,null=True,blank=True) created = models.DateTimeField(null=True,blank=True) last_use = models.DateTimeField(null=True,blank=True, default=None) And the worst, i edit the old one: class Application_Delete_History(models.Model): name = models.CharField(max_length=128) delete_time = models.DateTimeField(null=True) status = models.BooleanField(default=True) # Add: is_fa = models.NullBooleanField(null=True, blank=True) is_ide = models.NullBooleanField(null=True, blank=True) applicant = models.CharField(max_length=64, blank=True) # with out : null=True, defect_manager = models.ForeignKey(Review_Manager,null=True, default=None) admin_comment = models.CharField(max_length=256, null=True, blank=True) And run: python3.4 manage.py migrate (i did makemigrations and sqlmigrate) And the ERROR show up: ForeignKey can't be fill (The data allready exit conflix with it) ~> The models change but Migare FAIL. Now i want to fix this problem BUT: When i delete the new migrations and create a new one 1 got: I am sure that i edited defect_manager = models.ForeignKey(Review_Manager,null=True, default=None) And: File "/usr/local/lib/python3.4/site-packages/MySQLdb/connections.py", line 280, in query _mysql.connection.query(self, query) django.db.utils.OperationalError: (1060, "Duplicate column name 'admin_comment'") This issue DON'T HAPPEN in Django …