Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Selenium: testing django form, file not upload
I have a form similar to django admin form, where user can create object and attach related models to it using separate forms in popup windows. In my form user can attach file to model. He clicks in plus button... and such popup form shows up: After file upload and submit form, new file is created and displayed in select input: Now, I want to test this behaviour using selenium. However, when popup closes after form submit, select input is still empty. This is how I attach file in my test: # select plus btn plus_btn = self.browser.find_element_by_css_selector( ".related-widget-wrapper select#id_files + a") plus_btn.click() self.switch_to_popup() file_input = self.browser.find_element_by_css_selector( "input[name='_file']") file_input.send_keys(os.getcwd() + "/test.txt") self.browser.find_element_by_css_selector( "input[type='submit']").click() self.switch_to_main() PS: The problem is not in self.switch_to_popup and self.switch_to_main. These are valid, working methods created by me. -
Can I review and delete Celery / RabbitMQ tasks individually?
I am running Django + Celery + RabbitMQ. After modifying some task names I started getting "unregistered task" KeyErrors, even after removing tasks with this key from the Periodic tasks table in Django Celery Beat and restarting the Celery worker. It turns out Celery / RabbitMQ tasks are persistent, and the issue can be resolved by restarting with the --purge option. In future, I'd prefer not to purge the whole queue or restart the worker. Instead I'd like to inspect the queue and individually delete any legacy tasks. Is this possible? (Preferably in the context of the Django admin interface.) -
How to read session language in a class form __init__ function
in my Django project I dynamically create the fields of ContactsForm class: class ContactsForm(forms.Form): def __init__(self, *args, **kwargs): super(ContactsForm, self).__init__(*args, **kwargs) self.fields['nome'].widget.attrs.update({ 'class' : 'form-control', 'placeholder': 'your name *', 'type': 'text' }) [..] In the template: [..] #set language <a href="/language/it">ITA</a> - <a href="/language/en">ENG</a> {% if session_language == 'it' %} [..] {% else %} [..] {% endif %} <form id="contactForm" name="sentMessage" method='POST' action=''>{% csrf_token %} [..] <div class="form-group" > {{ form.nome }} </div> [..] </form> How can I pass the session_language attribute to the ContactForm class so that I can use it as a flag to switch between the italian and english versions of the fields? if lang == 'it': self.fields['nome'].widget.attrs.update({ 'class' : 'form-control', 'placeholder': 'il tuo nome *', 'type': 'text' }) else: self.fields['nome'].widget.attrs.update({ 'class' : 'form-control', 'placeholder': 'your name *', 'type': 'text' }) Thank you for any help you can provide. -
Django Error: could not convert string to float in source code not in my own code
When I try run python manage.py migrate to synchronize database I get error File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/Library/Python/2.7/site-packages/django/core/management/__init__.py", line 354, in execute_from_command_line utility.execute() File "/Library/Python/2.7/site-packages/django/core/management/__init__.py", line 346, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Library/Python/2.7/site-packages/django/core/management/base.py", line 394, in run_from_argv self.execute(*args, **cmd_options) File "/Library/Python/2.7/site-packages/django/core/management/base.py", line 445, in execute output = self.handle(*args, **options) File "/Library/Python/2.7/site-packages/django/core/management/commands/migrate.py", line 222, in handle executor.migrate(targets, plan, fake=fake, fake_initial=fake_initial) File "/Library/Python/2.7/site-packages/django/db/migrations/executor.py", line 110, in migrate self.apply_migration(states[migration], migration, fake=fake, fake_initial=fake_initial) File "/Library/Python/2.7/site-packages/django/db/migrations/executor.py", line 148, in apply_migration state = migration.apply(state, schema_editor) File "/Library/Python/2.7/site-packages/django/db/migrations/migration.py", line 115, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "/Library/Python/2.7/site-packages/django/db/migrations/operations/fields.py", line 62, in database_forwards field, File "/Library/Python/2.7/site-packages/django/db/backends/sqlite3/schema.py", line 179, in add_field self._remake_table(model, create_fields=[field]) File "/Library/Python/2.7/site-packages/django/db/backends/sqlite3/schema.py", line 77, in _remake_table self.effective_default(field) File "/Library/Python/2.7/site-packages/django/db/backends/base/schema.py", line 211, in effective_default default = field.get_db_prep_save(default, self.connection) File "/Library/Python/2.7/site-packages/django/db/models/fields/__init__.py", line 710, in get_db_prep_save prepared=False) File "/Library/Python/2.7/site-packages/django/db/models/fields/__init__.py", line 702, in get_db_prep_value value = self.get_prep_value(value) File "/Library/Python/2.7/site-packages/django/db/models/fields/__init__.py", line 1804, in get_prep_value return float(value) ValueError: could not convert string to float: Jestem watowcem But in my own code I haven't got any String like "Jestem watowcem". I have just removed it for test. Only one file from Error List is editable and it is manage.py but I haven't edited it since beggining of project. I didn't … -
DatabaseError: ORA-00942: table or view does not exist
I have a problem running a sample test. import unittest from automation.models import Accountproperty class TestEx(unittest.TestCase): def test_get_data_from_database(self): Accountproperty.objects.count() if __name__ == "__main__": unittest.main() When I run this test from shell I have no problem: C:\Users\apodar\PycharmProjects\autoTest>python manage.py shell Python 2.7.5 (default, May 15 2013, 22:44:16) [MSC v.1500 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) >>> from automation.models import * >>> Accountproperty.objects.count() 490 >>> But when I run the test in this manner I have the following issue: C:\Users\apodar\PycharmProjects\autoTest>python manage.py test interface.tests.testEx.TestEx Creating test database for alias 'default'... Creating test user... System check identified no issues (0 silenced). E ====================================================================== ERROR: test_get_data_from_database (interface.tests.testEx.TestEx) ---------------------------------------------------------------------- Traceback (most recent call last): File "C:\Users\apodar\PycharmProjects\autoTest\interface\tests\testEx.py", line 7, in test_get_data_from_database Accountproperty.objects.count() File "C:\Python27\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Python27\lib\site-packages\django\db\models\query.py", line 364, in count return self.query.get_count(using=self.db) File "C:\Python27\lib\site-packages\django\db\models\sql\query.py", line 499, in get_count number = obj.get_aggregation(using, ['__count'])['__count'] File "C:\Python27\lib\site-packages\django\db\models\sql\query.py", line 480, in get_aggregation result = compiler.execute_sql(SINGLE) File "C:\Python27\lib\site-packages\django\db\models\sql\compiler.py", line 894, in execute_sql raise original_exception DatabaseError: ORA-00942: table or view does not exist ---------------------------------------------------------------------- Ran 1 test in 0.119s FAILED (errors=1) Destroying test database for alias 'default'... Destroying test user... Destroying test database tables... C:\Users\apodar\PycharmProjects\autoTest> Please find … -
How to display Local datetime in django template from UTC datetime stored in database?
I want to display date time in visitors local timezone in DJango templates from date time stored in UTC format in Database. for that i have made following changes in different files. settings.py TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True page.html {% load tz %} <div> {{ start_time | localtime }} </div> and <div> {% localtime on %} {{ start_time }} {% endlocaltime %} </div> As this start_time is stores only 'HH:MM' in string format. But i have also tried with the date time object. still it doesn't works for me. and one more issue, when i use datetime.utcnow() and datetime.now(), both gives me 'UTC' date time in views.py. or suggest me, if any other way to get the same? So can anyone please help me to solve this issue ? Any help would be highly appreciated. Thank you. -
How to test ArrayField Django 1.11
Django 1.11 I am testing the forms which is Meta by ArrayList in the Model. I have cut out the unrelated code from my question. models.py class MailAPIScheduler(DirtyFieldsMixin, AbstractSoftModelController): summary_email_receivers = ArrayField( models.EmailField(blank=True), blank=True ) forms.py import json from django import forms from eneos.apps.mail_api_schedule.models import MailAPIScheduler class MailAPISchedulerForm(forms.ModelForm): schedule_time = forms.TimeField() class Meta: model = MailAPIScheduler fields = [ 'api_url', 'schedule_time', 'parameters', 'summary_email_receivers', ] def clean_schedule_time(self): dt = self.cleaned_data['schedule_time'] return { 'hour': dt.hour, 'minute': dt.minute, } tests.py def test_mail_api_scheulder_form(self): data = { 'api_url': 'http://hotmail.com', 'schedule_time': '9:30', 'parameters': json.dumps({'key1': 'value1', 'key2': 'value2'}), 'summary_email_receivers': ["elcolie@gmail.com", "sarit.r@codium.co"] } form = MailAPISchedulerForm(data) import pdb; pdb.set_trace() self.assertEqual(True, form.is_valid()) self.assertDictEqual(form.cleaned_data.get('schedule_time'), { 'hour': 9, 'minute': 30, }) Run tests $ python manage.py test eneos.apps.mail_api_schedule.tests.TestMailAPIScheduler.test_mail_api_scheulder_form --nomigrations --settings=eneos.config.settings.local Hey, I'm Local! Creating test database for alias 'default'... > /Users/el/Code/eneos-pos-web/eneos/apps/mail_api_schedule/tests.py(188)test_mail_api_scheulder_form() -> self.assertEqual(True, form.is_valid()) (Pdb) n AttributeError: 'list' object has no attribute 'split' Where am I wrong? -
Single sign-on between WordPress and Django
I have two web applications on Apache Ubuntu 16.04 Server: WordPress 4.8.1 website Django 1.11 application (with django-rest-framework) I want to install a Single Sign-On service (SSO). For instance, User logs on WordPress, then when he goes to Django website, he is already connected. Actually I don't find anything about SSO between WordPress and Django. Do you have an idea how to do it ? -
Django restful api can not get file content
I use Django restful api + angularjs . Now ,I append to use angularjs upload file to server by Django restful api On the web front-end ,The Html is: <input type="file" data-upload-file id="uploadInputFile"> The angularjs's code is : omapp.directive("uploadFile",function(httpPostFactory){ return { restrict:"A", scope:true, link:function(scope,element,attr){ element.bind('change',function(){ var formData = new FormData(); formData.append('file', element[0].files[0]); console.log(formData.get('file')) httpPostFactory('/api/uploadfile/',formData.get('file'),function (callback) { console.log(callback); }) }) } }; }); omapp.factory('httpPostFactory', function ($http,$cookies) { return function (file, data, callback) { var req = { method:"POST", url:file, headers:{ 'X-CSRFToken':$cookies.get('csrftoken') }, data:{file:data} } $http(req) .then(function successcallback(response){callback(response);}) } }); Everything is ok .But Django api can not get data The code is : class UploadFile(APIView): def post(self,request,format=None): logger.info("file content"); logger.info(request.data) return Response("upload done") How can i get data ? -
Can Django support symbolic link models.py and migrations directory?
I have 3 django projects and one database. I want to share database from each apps. So, I made database from app3 and made symbolic links of models.py and migrations directory from app1 and app2. I use only app3 when I want to migrate database. This seems to work well. I can also make superuser from app3. But when I want to create superuser(manage.py createsuperuser) from app1 and app2, I got the following error. django.db.migrations.exceptions.NodeNotFoundError: Migration remoshin_user_sys.0004_auto_20170827_2351 dependencies reference nonexistent parent node ('remoshin_manager_sys', '0003_auto_20170827_2349') I want to know my approach can work when 3 apps share one database. Would you help me please? -
How can I use a Django template variable in HTML in a model TextField?
I want to generate external urls programatically instead of hard-coding them in HTML in case any one of them should change at some point In my template I have this. <p> {{ article.text|safe }} </p> My Article class is this. class Article(models.Model): title = models.CharField(max_length=200) teaser = models.TextField(default = "") text = models.TextField() category = models.CharField(max_length=100) image_name = models.CharField(default = "", max_length=100) published_date = models.DateField(blank=True, null=True) My View class is this. class Article_Page(TemplateView): model = Article template_name="articles/article.html" def get_context_data(self, **kwargs): context = super(Article_Page,self).get_context_data(**kwargs) context['article'] = Article.objects.get(pk=kwargs['pk']) context['external_urls'] = External_Urls() return context class External_Urls(object): stack_overflow = 'https://stackoverflow.com' And in my TextField in the model I have this. <a href={{ external_urls.stack_overflow }}>Stack Overflow</a> That line of HTML gives a link to https://stackoverflow.com if I include it directly in the template, but if it is in the model TextField the link goes to 'http://127.0.0.1:8000/articles/pk/{{'. How can I escape template variables in TextField HTML? -
How to create Django superuser in Ansible in idempotent way?
I am using Ansible to deploy my Django app. I have this step in my Ansible playbook for creating a superuser: - name: django create superuser django_manage: virtualenv: /.../app app_path: /.../app command: "createsuperuser --noinput --username=admin --email=admin@{{ inventory_hostname }}" But when I run my playbook a second time it fails with database constraint error since a superuser with given username already exists. How do I make this step idempotent? -
OSError: [Errno 13] Permission denied: '/usr/local/lib/python2.7/site-packages/django'
Exception: Traceback (most recent call last): File "/usr/local/lib/python2.7/site-packages/pip/basecommand.py", line 215, in main status = self.run(options, args) File "/usr/local/lib/python2.7/site-packages/pip/commands/install.py", line 342, in run prefix=options.prefix_path, File "/usr/local/lib/python2.7/site-packages/pip/req/req_set.py", line 784, in install **kwargs File "/usr/local/lib/python2.7/site-packages/pip/req/req_install.py", line 851, in install self.move_wheel_files(self.source_dir, root=root, prefix=prefix) File "/usr/local/lib/python2.7/site-packages/pip/req/req_install.py", line 1064, in move_wheel_files isolated=self.isolated, File "/usr/local/lib/python2.7/site-packages/pip/wheel.py", line 345, in move_wheel_files clobber(source, lib_dir, True) File "/usr/local/lib/python2.7/site-packages/pip/wheel.py", line 316, in clobber ensure_dir(destdir) File "/usr/local/lib/python2.7/site-packages/pip/utils/__init__.py", line 83, in ensure_dir os.makedirs(path) File "/usr/local/lib/python2.7/os.py", line 157, in makedirs mkdir(name, mode) OSError: [Errno 13] Permission denied: '/usr/local/lib/python2.7/site-packages/django' How can I install Django?!?!?! -
set "approved" or "denied" or "pending" under Status column Django
I am currently figuring out a way to show the status whether it is "approved" or "denied" or "pending" under the Status column according to which button the user has selected. If user has not selected any of the button, "pending" will be shown. If approve button has been selected, deny button will be disabled and "approved" will be shown under Status column. Right now when I select either "approve" or "deny" button, nothing appear under the Status column and not a single button being disabled. .html file <form method="POST" action=""> {% csrf_token %} <table id="example" class="display" cellspacing="0" width="100%" border="1.5px"> <tr align="center"> <th> Student ID </th> <th> Student Name </th> <th> Start Date </th> <th> End Date </th> <th> Action </th> <th> Status </th> </tr> {% for item in query_results %} <tr align="center"> <td> {{item.studentID}} </td> <td> {{item.studentName}} </td> <td> {{item.startDate|date:'d-m-Y'}} </td> <td> {{item.endDate|date:'d-m-Y'}} </td> <td> <input type="submit" name="approve" value="approve"> <input type="submit" name="deny" value="deny"> </td> /*i have no idea what should i write in Status column*/ <td> </td> </tr> {% endfor %} </table> </form> models.py class SuperLTimesheet(models.Model): timesheet = models.ForeignKey(Timesheet, on_delete=models.CASCADE) status = models.TextField("Status", default="pending") views.py def superltimesheet(request): query_results = Timesheet.objects.all() data={'query_results':query_results} if request.POST.get('approve'): Superltimesheet.status = "approved" return redirect('hrfinance/supervisor_list_timesheet.html') elif … -
'ascii' codec can't encode characters in position 0-3: ordinal not in range(128)
I use the jquery to post request to a url(/sendOrder/): params = { "username": $("#username").val(), "tel":$("#tel").val(), "email":$("#email").val(), "address":$("#address").val(), "content":$("#content").val() }; $.post("/sendOrder/",params,function(result){ alert(result); }); But when I request, I get a error: Failed to load resource: the server responded with a status of 500 (Internal Server Error) And in the detail, there is message: UnicodeEncodeError at /sendOrder/ 'ascii' codec can't encode characters in position 0-3: ordinal not in range(128) The urls.py: urlpatterns = [ ... url(r'^sendOrder/', f_end_v.sendOrder) ] In the views.py: def sendOrder(request): if request.method == 'POST': pass From the similar post:Django Admin. UnicodeEncodeError 'ascii' codec can't encode characters in position 0-3: ordinal not in range(128) I have checked # -*- coding: utf-8 -*- in my views.py. Some friend know why I get this error? EDIT-1 All of the traceback: UnicodeEncodeError at /sendOrder/ 'ascii' codec can't encode characters in position 0-3: ordinal not in range(128) Request Method: POST Request URL: http://localhost:8000/sendOrder/ Django Version: 1.11.2 Python Executable: /usr/bin/python Python Version: 2.7.10 Python Path: ['/Users/luowensheng/Desktop/TestIOS/TestPython/gjjWeb', '/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg', '/Library/Python/2.7/site-packages/Django-1.11.2-py2.7.egg', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python27.zip', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-darwin', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac/lib-scriptpackages', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-old', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload', '/Library/Python/2.7/site-packages', '/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python', '/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/PyObjC'] Server time: Mon, 28 Aug 2017 08:16:31 +0000 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'frontend'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] … -
How to duplicate the field which is primarykey field?
I have a table with two primary key values(i.e; composite key),field names are id,date. So i want to save the same 'id' with different 'date' with in the next record also how can i overcome this? -
Django: ModelForm change based on menu selection
I'm developing a website with Django + Crispy-Forms. I want a form that can: dynamically change which fields are visible based on the selection of a dropdown menu. save the entered data into a database. Only data entered into visible fields should be saved. Is there a way to accomplish this using forms.ModelForm? One possible 'solution' involves, in order: assigning each form field a HTML attribute in forms.py using JS to selectively hide/show fields based on the selection in the dropdown menu and the custom attributes views.py will then selectively save entries to a database. However, this feels really 'hacky' and I'm wondering if there's another, more elegant method? There is also the question of how crispy-forms will work into all of this. If this is better done using forms.Form instead of forms.ModelForm, then cool. I don't think this multi-faceted question has been answered in its entirety in any previous question; apologies if it has! Also, thanks for any help. -
Wagtail ModelAdmin not showing fields when editing one object, but does show fields when showing all
I'm using Wagtail, and I'm also using django-inspectional-registration. I'm trying to set it up so that approving users can be done in the CMS, and not the django admin. To do this I've created a ModelAdmin, as seen here: wagtail_hooks.py from wagtail.contrib.modeladmin.options import (ModelAdmin, modeladmin_register) from registration.models import RegistrationProfile class RegUserModelAdmin(ModelAdmin): model = RegistrationProfile menu_label = 'Users to accept' menu_icon = 'user' menu_order = 250 add_to_settings_menu = False exclude_from_explorer = False list_display = ("user", "_status") list_filter = ("_status",) search_fields = ("user",) modeladmin_register(RegUserModelAdmin) Then as expected all registration profiles are seen like so: However if I click on any of these profiles, it shows me nothing: No errors appear in the browser console, or my test server, absolutely nothing. I have another ModelAdmin that works perfectly with another model of mine, which makes this even more confusing. -
'User' object has no attribute 'leave'
I am making a leave application module and I got User has no attribute errors, I have searched a lot of things but unable to get a proper answer. I a new to django and have no idea about where i am doing the things wrong. This is the code for the models.py Code For the models from django.db import models from django.contrib.auth.models import User; from django.db.models.signals import post_save from django.dispatch import receiver LEAVE_CHIOCE = ( ('casual', 'Casual Leave'), ('vacation', 'Vacation Leave'), ('commuted', 'Commuted Leave'), ('special_casual', 'Special Casual Leave'), ('restricted', 'Restricted Leave'), ('st ation', 'Station Leave'), ) APPLICATION_STATUSES = ( ('accepted', 'Accepted'), ('rejected', 'Rejected'), ('processing', 'Being Processed') ) class Leave(models.Model): user = models.OneToOneField(User,related_name='applied_for', on_delete=models.CASCADE); leave_type = models.CharField(max_length=20, choices=LEAVE_CHIOCE); applied_time = models.DateTimeField(auto_now = True); start_date = models.DateField(); end_date = models.DateField(); purpose = models.CharField(max_length=500, blank=True); leave_address = models.CharField(max_length=100, blank=True); processing_status = models.CharField(max_length=20, choices=APPLICATION_STATUSES); @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Leave.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.leave.save() This is the code for the forms.py from django import forms; from . models import Leave, ApplicationRequest, RemainingLeaves; from django.contrib.auth.models import User; from django.contrib.auth.forms import UserCreationForm; from datetime import datetime class UserForm(forms.ModelForm): class Meta: model = User; fields = ('username', 'first_name', 'last_name', … -
Return different reponse or data depending on method - Django rest framework
Please help. What I need to do is to get different responses or data depending on the method- something like this: if request.method == 'POST': return all the items created including the last one (actually it returns only the last item created) else if request.method == 'PUT': return the last item updated this is my code **Views.py** class RubroViewSet(viewsets.ModelViewSet): queryset = Rubro.objects.all() serializer_class = RubroSerializer **models.py** class Rubro(models.Model): nombre = models.CharField(max_length=50) descripcion = models.TextField() class Meta: verbose_name_plural = 'Rubros' db_table = "core_rubros" def __str__(self): return self.nombre **serializers.py** class RubroSerializer(serializers.ModelSerializer): class Meta: model = Rubro fields = '__all__' -
Django module not retrieving data from API
I have a class that I call from my project that is executed through the url: data/refresh urls.py from django.conf.urls import url, include from . import views from rest_framework import routers router = routers.DefaultRouter() urlpatterns = [ url(r'^refresh/$', views.refresh), url(r'^$', views.index, name='index'), url(r'^', include(router.urls)), url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')), ] and my views.py def refresh(request): gatorate = Gatorate() r = gatorate.start() if r["code"] < 0: return {"code":-1,"error":r["error"]} # while spider.has_next_page() == True: data = gatorate.run() # #run last page # spider.run() return JsonResponse({"code":1,"data":data} The class runs and populates my database when I run in Development, and in production, if I start python, import my module, and execute it, it will run and populate my database. I am wondering if there is a permission issue that is not allowing me to run the script. Also, if anyone can suggest a way to automate this to run everyday, I was planning on using CRON, but I like the flexibility to execute it from the url remotely. spider.spider.py: import sqlite3 import MySQLdb import time import os import django os.environ["DJANGO_SETTINGS_MODULE"] = 'web.settings' django.setup() from django.utils import timezone from webservice.models import BSR from vardata import ASINS class Gatorate: def __init__(self): self.amazon = None self.product = None self.asins … -
python django wsgi multithread - how to use multithread in django
I have a django application in which i am using python Thread module to do multi threading, it works fine while using django development server through manage.py. But when i deploy on apache - mod_wsgi, its not working .join is failing and threading not working. Can anyone help for exact apache configuration ? i tried keeping some multithread and multiprocess configuration like follows. But still not working. My configuration - Listen 8000 Alias /static/ /usr/td/static/ <Directory /usr/td/static/> Require all granted </Directory> <Directory /usr/td> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess td display-name=myproject processes=10 threads=255 python-path=/usr/td/:/usr/lib/python2.7/site-packages WSGIProcessGroup td WSGIScriptAlias / /usr/td/td/wsgi.py -
In the browser lost the template's class
The li has a class="on" in the template: <li class="on" > <a href="/contact/" name="message">联系我们</a> <div class="secondary-menu"> <ul><li><a href="message.html" class="message"></a></li></ul> </div> </li> But when I test in the browser, there is only class here, lost the ="on". It is strange, right? -
how do i set default value of "pending" to the Status column Django
I would like to have a default value which is "pending" being shown under the Status column when the user has not select either approve or deny button under the Action column. I have tried doing "status = models.TextField("Status", max_length=100, default="pending")" in my models.py under class SuperLTimesheet but the word "pending" is not being shown under Status column. models.py class SuperLTimesheet(models.Model): timesheet = models.ForeignKey(Timesheet, on_delete=models.CASCADE) status = models.TextField("Status", max_length=100, default="pending") html file <form method="POST" action=""> {% csrf_token %} <table id="example" class="display" cellspacing="0" width="100%" border="1.5px"> <tr align="center"> <th> Student ID </th> <th> Student Name </th> <th> Start Date </th> <th> End Date </th> <th> Action </th> <th> Status </th> </tr> {% for item in query_results %} <tr align="center"> <td> {{item.studentID}} </td> <td> {{item.studentName}} </td> <td> {{item.startDate|date:'d-m-Y'}} </td> <td> {{item.endDate|date:'d-m-Y'}} </td> <td> <input type="submit" name="approve" value="approve"> <input type="submit" name="deny" value="deny"> </td> <td> {{item.action}} </td> </tr> {% endfor %} </table> </form> -
Uncaught ReferenceError: $ is not defined for initializing datatables, django [duplicate]
This question already has an answer here: JQuery - $ is not defined 34 answers I'm trying to initialize datatables in my django template, but I'm getting Uncaught ReferenceError: $ is not defined at (index):121. I've read some question/answers from SO, and as I can see it my jquery and datatables are loading properly and I'm handling it like this {% block javascript %} <!-- Required by Bootstrap v4 Alpha 4 --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script src="https://cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js" integrity="sha384-DztdAPBWPRXSA/3eYEEUWrWCy7G5KFbe8fFjk5JAIxUYHKkDx6Qin1DkWx51bBrb" crossorigin="anonymous"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" crossorigin="anonymous"></script> <!-- Your stuff: Third-party javascript libraries go here --> <script src="{% static 'bower_components/underscore/underscore-min.js' %}"></script> <!-- place project specific Javascript in this file --> <script src="{% static 'js/project.js' %}"></script> {% endblock javascript %} The error is occur on the first script line $(document).ready(function() { so this is returning ReferenceError, all I can think off is that jquery is not been initialize but why? So can someone help me understand what is going on, thanks. My template {% extends "base.html" %} {% load crispy_forms_tags %} {% block ng_app %}company{% endblock %} {% block content %} <div class="container"> <div class="row"> <p style="padding:10px;"></p> </div> </div> <div class="container"> <div class="row"> <div class="col-sm-8 col-sm-offset-2"> <form action="{% url 'company:create-employee' %}" method="post"> {% csrf_token …