Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Web development framework and technologies
I learned HTML and CSS but still I am new to web development. Anybody please tell me what a framework is? I don't know why developers use frameworks like ruby on rails, django, flask for developing websites and what are the advantages of using these frameworks. -
DecimalField won't accept a float
I have a model: Model(models.Model) price = models.DecimalField(max_digits=10, decimal_places=2) and I have a string: new_price = "39.99" When I try the following: model_instance.price = float(new_price) model_instance.save() I get django.core.exceptions.ValidationError: {'price': ['Ensure that there are no more than 10 digits in total.']} Why? -
Django QuerySet TypeError
we are getting the weirdest error ever. Our whole dev team was on this for the past two days and we cannot get over it. We have our DRF serializer with a following function: def get_custom_fields(self, obj): custom_fields = obj.company.ticketcustomfieldtype_set.all() return [{ 'id': field.id, 'name': str(field.name), 'type': field.type, 'value': obj.custom_fields[str(field.id)] if str(field.id) in obj.custom_fields else None } for field in custom_fields] custom_fields there is a regular Django QuerySet Now the weird thing: On localhost, this works just fine. On remote, it works fine only when the QuerySet is empty. If there is something in it, we get the following error: TypeError: string indices must be integers It appears that the custom_fields is now a string. We have no idea why, because on local it works just fine... Django 1.11.5 DRF 3.6.4 Python 3.4.3 Postgres 9.6.5 Any help much appreciated, getting desperate :( -
Python - Django - TypeError: coercing to Unicode: need string or buffer, long found
I'm currently working on a django application and I'm stuck with these error : TypeError: coercing to Unicode: need string or buffer, long found Here is my code : class eleve(models.Model): ideleve = models.IntegerField(db_column='idEleve',primary_key=True) cp = models.IntegerField(blank=True, null=True) ville = models.CharField(max_length=45, blank=True, null=True) pays = models.CharField(max_length=45, blank=True, null=True) annee = models.CharField(max_length=4, blank=True, null=True) specialite = models.CharField(max_length=45, blank=True, null=True) def __unicode__(self): return unicode(self.ideleve) class Meta: db_table = 'statistique_eleve' Traceback : >>> eleve.objects.all() Traceback (most recent call last): File "<console>", line 1, in <module> File "/home/eisti/.local/lib/python2.7/site-packages/django/db/models/query.py", line 229, in __repr__ return '<%s %r>' % (self.__class__.__name__, data) File "/home/eisti/.local/lib/python2.7/site-packages/django/db/models/base.py", line 590, in __repr__ u = six.text_type(self) TypeError: coercing to Unicode: need string or buffer, long found -
PhantomJS webdriver error code -11 when I use uWSGI http request to launch phantomJS to grab web data
Traceback (most recent call last): File "tb_list_spider.py", line 42, in parse_tblist driver = webdriver.PhantomJS(desired_capabilities=desired_capabilities) File "/usr/local/lib/python3.6/site-packages/selenium/webdriver/phantomjs/webdriver.py", line 52, in __init__ self.service.start() File "/usr/local/lib/python3.6/site-packages/selenium/webdriver/common/service.py", line 96, in start self.assert_process_still_running() File "/usr/local/lib/python3.6/site-packages/selenium/webdriver/common/service.py", line 109, in assert_process_still_running % (self.path, return_code) selenium.common.exceptions.WebDriverException: Message: Service phantomjs unexpectedly exited. Status code was: -11 Message: Service phantomjs unexpectedly exited. Status code was: -11 Above is the traceback info. When I use command line way to run my code is fine, but it is not work when I use browser http request to trigger the phantomJS by uWSGI interface. the error code is -11,but I dont know where to find the meanning of -11. who knows the error code meaning please told me,thanks very much. the enviroment:centos7 + python3.6.2 + phantomJS-2.1.1 + uWSGI-2.0.15 +Django-1.11.7 -
django reusing form template to display data?
So I have about a dozen forms for user input like this that I've created over some time now (Had to manually do because the forms have to look a certain way). Example: <div class=""> <h4 class="row">Provide data for Installation Report</h4> <form action="" method="POST"> {% csrf_token %} <div> <p class="row">Onsite Installation (Completed by Installer)<br> Installer must complete one “Service Provider” Section for each unit installed</p> <div class="row z-depth-2 input-grouping"> <div class="col s12 m12 l6 "> <input class="datepicker" id="id_installationDate" name="installationDate" type="text" required /> <label for="id_installationDate">Date of Installation</label> </div> <div class="col s12 m12 l6 "> <input id="id_deliveryOrder" maxlength="255" name="deliveryOrder" type="text" /> <label for="id_deliveryOrder">Delivery Order</label> </div> </div> <div class="row z-depth-2 input-grouping"> <div class="col s12 m12 l6 "> <input id="id_unitSerialNumber" maxlength="255" name="unitSerialNumber" type="text" required /> <label for="id_unitSerialNumber">Unit Serial Number</label> </div> <div class="col s12 m12 l6"> <input id="id_unitHours" name="unitHours" step="0.01" type="number" required /> <label for="id_unitHours">Unit Hours</label> </div> </div> And so on ... This form for example, saves data to InstallationReport model. Now I need to display an InstallationReport object somewhere. It'd be great if I don't have to copy-paste the html in the form above (and then bind data). Instead, if I can just use the form itself to show the object, it'd be easier … -
Django upload data into memory
Is it possible in Django to load data into the Memory, process it and return it to the User? Example: User uploads image -> Python Script process it (e.g. make it s/w) -> User sees processed Image on same Webpage (Other Examples would be all these "convert-online" sites like pdf2doc.com) Is it a bad idea to load it into the Memory? Would a Queue and saving it on a CDN be a better solution? I'm trying to understand the possibilities of handling files from the User, which don't need to be safed. I appreciate any further ideas/considerations. -
Show product detail in the modal
The usecase of my app is to show a list of furnitures in the homepage. There is quick preview button in all those furnitures which when clicked should show its detail information. I tried to use ajax for that. If i click on the furniture quick preview button, I get the clicked furniture slug from which I do the query and get that furniture detail information. Upto this, its working and also the modal is shown but could not show the content. How can i now show the content in the modal-body? Here is what I have tried def ajax_furniture_detail(request): furniture_slug = request.GET.get('slug', None) qs = Furniture.objects.get(slug=furniture_slug) cart_obj, new_obj = Cart.objects.new_or_get(request) context = { 'furniture': model_to_dict(qs), 'cart': model_to_dict(cart_obj), 'status': 'ok' } return JsonResponse(context) {% block content %} {% include 'furnitures/furnitures_home.html'%} {% endblock content %} {% block js %} {{ block.super }} <script> $(document).ready(function(){ $('.quick-view-button').click(function() { var _this = $(this); var slug = _this.attr("data-slug"); $.ajax({ url: '/ajax/furniture', type: "get", data: {'slug': slug}, success: function(data) { $('#product-quick-view-modal').modal('show'); $('#product-quick-view-modal').find('.modal-body').html(data.html); }, error: function(err) { console.log('error', err); } }) }) }); </script> {% endblock js %} furnitures_home.html {% load static %} <div class="furnitures" id="content"> {% for furniture in furnitures %} {% if forloop.first %}<div class="row … -
Django project doesn't work on digital server
I can't resolve this error, if i run it with "python3 manage.py runserver 0.0.0.0:8000" it run on my_site_ip :8000 :/home/django/django_project# sudo tail -F /var/log/nginx/error.log 2017/11/30 08:58:31 [error] 2147#2147: *116 connect() to unix:/home/django/gunicorn.socket failed (111: Connection refused) while connecting to upstream, client: 46.254.153.21, server: _, request: "GET / HTTP/1.1", upstream: "http://unix:/home/django/gunicorn.socket:/", host: "45.55.171.120" 2017/11/30 09:30:14 [alert] 2147#2147: *131 open socket #11 left in connection 6 2017/11/30 09:30:14 [alert] 2147#2147: aborting This is the directory /home/django/django_project# ls -l total 832 drwxr-xr-x 5 root root 4096 Nov 30 09:00 app -rw-r--r-- 1 root root 745472 Nov 29 23:20 db.sqlite3 -rw-r--r-- 1 root root 40520 Nov 29 23:20 listautenti.xlsx -rwxr-xr-x 1 root root 817 Nov 29 23:20 manage.py -rw-r--r-- 1 root root 44652 Nov 29 23:20 pass.txt -rw-r--r-- 1 root root 302 Nov 29 23:20 pw.py drwxr-xr-x 3 root root 4096 Nov 30 08:36 SettimanaFlessibile -rw-r--r-- 1 root root 0 Nov 30 09:17 SettimanaFlessibliele.sock drwxr-xr-x 2 root root 4096 Nov 29 23:20 tabelle -
Trigger view function with bootstrap button
I don't really get how to make a button click trigger my view function... I already googled, but nothing really helps me understand... In my html, I have: <a class="btn btn-large btn-info" href="{% url "device-detail" device.pk %}" name = 'rotateleft'>Rotate Left</a> And in my views.py: class DeviceDetail(DetailView): .... def rotate_left(request, self): if request.GET.get('rotateleft') == 'rotateleft': print 'TEST!!!!' self.image.open() self.image.rotate(-90) self.image.save() If I click the button, the page seems to be reloaded as planned, but as 'TEST' is not printed (and the image is not rotated, but it might be that the code that is supposed to rotate it doesn't work yet, I wanted to call the function to see if it works), I'm guessing that this function is never called. I am relatively new to Django and very new to the web interface side of Django, so help would be really appreciated! -
Why is variable name important in multiwidget template?
In my form i have a Multiwidget with 3 Textinputs. I want to customize html output so in 1.11 i have to use new template api. Clear so far. My custom multiwidget template(99% copy/paste from docs) looks like this: <div class="row"> {% for widget in widget.subwidgets %} <label class="col-md-2">Label</label> <div class="col-md-2"> {% include widget.template_name %} </div> {% endfor %} </div> But i don't like using the same variable name 'widget' for multiwidget and subwidget. So i replace {% for widget in widget.subwidgets %} {% include widget.template_name %} with {% for subwidget in widget.subwidgets %} {% include subwidget.template_name %} But it doesn't work. I get the same text input 3 times and this input has id, name and value from multiwidget, not from subwidgets(id without "_0", compressed value) Is it a bug or my misunderstanding? -
Terminal Command: Regarding the creation of a Django project [duplicate]
This question already has an answer here: What is double dot(..) and single dot(.) in Linux? 4 answers I cannot for the life me figure out where /usr/local/bin/ and various directories as such are to be found on MacOS (I know how to search for them in Finder). More to the point: django-admin startproject mysite will not produce a project in the mysite directory, however, if I add a period (.) as instructed in a previous book I've read; it works. Why is this? vs. django-admin startproject mysite . for clarification. -
How can I send email to multi addresses by smtplib?
I use bellow code I can send email to one account, but how can I send to multi account? import smtplib from email.mime.text import MIMEText _user = "67676767@qq.com" # _pwd = "orjxywulscbxsdwbaii" # _to = linux213@126.com" # msg = MIMEText("content") # msg["Subject"] = "邮件主题测试" # msg["From"] = _user msg["To"] = _to try: s = smtplib.SMTP_SSL("smtp.qq.com", 465) s.login(_user, _pwd) s.sendmail(_user, _to, msg.as_string()) s.quit() print ("Success!") except smtplib.SMTPException as e: print ("Falied,%s" % e) -
Can't restore a db from scratch on an existing Django project
I've got an existing Django 1.10 application and I want to create a new db locally from scratch. Following these steps $ createdb -h localhost -p 5432 -U me -w my_db # OK $ ./manage.py migrate I'm getting an exception Traceback (most recent call last): File "./manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/home/me/workspace/myproject-django/venv/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line utility.execute() File "/home/me/workspace/myproject-django/venv/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 341, in execute django.setup() File "/home/me/workspace/myproject-django/venv/local/lib/python2.7/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/home/me/workspace/myproject-django/venv/local/lib/python2.7/site-packages/django/apps/registry.py", line 115, in populate app_config.ready() File "/home/me/workspace/myproject-django/venv/local/lib/python2.7/site-packages/django/contrib/admin/apps.py", line 23, in ready self.module.autodiscover() File "/home/me/workspace/myproject-django/venv/local/lib/python2.7/site-packages/django/contrib/admin/__init__.py", line 26, in autodiscover autodiscover_modules('admin', register_to=site) File "/home/me/workspace/myproject-django/venv/local/lib/python2.7/site-packages/django/utils/module_loading.py", line 50, in autodiscover_modules import_module('%s.%s' % (app_config.name, module_to_search)) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/home/me/workspace/myproject-django/customauth/admin.py", line 7, in <module> from core.admin import ShopInline File "/home/me/workspace/myproject-django/core/admin.py", line 242, in <module> admin.site.register(Campaign, CampaignAdmin) File "/home/me/workspace/myproject-django/venv/local/lib/python2.7/site-packages/django/contrib/admin/sites.py", line 108, in register admin_obj = admin_class(model, self) File "/home/me/workspace/myproject-django/core/admin.py", line 104, in __init__ last_task = TaskState.objects.filter(name='core.tasks.compute_metrics', state='SUCCESS').order_by('tstamp').last() File "/home/me/workspace/myproject-django/venv/local/lib/python2.7/site-packages/django/db/models/query.py", line 565, in last objects = list((self.reverse() if self.ordered else self.order_by('-pk'))[:1]) File "/home/me/workspace/myproject-django/venv/local/lib/python2.7/site-packages/django/db/models/query.py", line 256, in __iter__ self._fetch_all() File "/home/me/workspace/myproject-django/venv/local/lib/python2.7/site-packages/django/db/models/query.py", line 1087, in _fetch_all self._result_cache = list(self.iterator()) File "/home/me/workspace/myproject-django/venv/local/lib/python2.7/site-packages/django/db/models/query.py", line 54, in __iter__ results = compiler.execute_sql() File "/home/me/workspace/myproject-django/venv/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 835, in execute_sql cursor.execute(sql, params) File "/home/me/workspace/myproject-django/venv/local/lib/python2.7/site-packages/django/db/backends/utils.py", line 79, … -
Django's ORM Model.objects.raw() query causes an infinite recursion error
I have the following (simplified) models: class Common(models.Model): id = models.BigAutoField(primary_key=True, editable=False) date_created = models.DateTimeField() user_created = models.CharField(max_length=200, null=True) service_created = models.CharField(max_length=200) def __init__(self, *args, **kwargs): super(Common, self).__init__(*args, **kwargs) self._initial_data = {} self.track_fields( 'date_created', 'user_created', 'service_created', ) def track_fields(self, *args): for field_name in args: self._initial_data[field_name] = getattr(self, field_name) class Directory(Common): directory_path = models.TextField() parent_directory = models.ForeignKey('self') Now, I'm trying to query some objects like this (a simplified example, pay no attention to why sql was used in the first place): sql_select_dirs_of_deleted_files = ''' select d.id, directory_path from directory d left join file f on f.parent_directory_id = d.id where f.removed = true and f.id in %s group by d.id, directory_path order by directory_path asc ''' dirs_of_deleted_files = Directory.objects.raw(sql_select_dirs_of_deleted_files, [tuple(file_ids)]) parent_of_top_dir = dirs_of_deleted_files[0].parent_directory Accessing dirs_of_deleted_files[0] causes an infinite recursion error on line self._initial_data[field_name] = getattr(self, field_name) in the Common model. I am aware of the recursion problems in inheritance and using getattr, but using models.Model.__getattribute__(self, field_name) does not seem to make a difference here. However, what DOES work instead is: dirs_of_deleted_files = Directory.objects \ .filter(files__in=file_ids, files__removed=True) \ .distinct('id', 'directory_path') \ .order_by('directory_path') Now, accessing dirs_of_deleted_files[0] does not cause any infinite recursion errors. The Common model is inherited by several other models, and instantiated … -
django shuffle query set and remember the pattern of shuffling
i have a code that displays questions from the database in random order the code that i have used is def platform(request,e,slug): tdetail=get_object_or_404(test_detail,test_id=article) ques=list(sorted(Upload.objects.filter(unique_id=tdetail), key=lambda x: random.random())) return render(request, 'articles/platform.html',{'ques':ques}) the ques variable takes all the questions in a list and then they are accessed at template.....but when the user refreshes the page the questions reshuffle...but i want that the same shuffled questions should be displayed again ........the shuffling of questions should occur only once and then even if user refreshes the page/url he should get the same questions as earlier -
How to Get value in 1 column with different table in Python
id | bill_num | Service ---------+----------------+------------ 1 | 92 | S1 2 | 93 | s4 id | bill_num | Product ---------+----------------+------------ 1 | 92 | p1 2 | 92 | p2 I need this table in python id | bill_num | Service/product ---------+----------------+------------ 1 | 92 | S1 2 | 92 | p1 3 | 92 | p2 4 | 93 | s4 -
Filter with 'date' in Django
In model.py, I create class Order has a field 'order_date' with DateTimeField. In views.py, I user query: orders = Order.objects.filter(order_day__date__gte = date_from, order_date__date__lte = date_to). The Query doesn't return any data, although in the database, between date_from and date_to has many records. -
django inplaceedit on newer version of django
I'm currently running Django 1.11 on python 2.7. Is the current version of django-inplaceedit supported? I'm trying to use it for my apps. Thanks in advance. -
How to use IntegerRangeField in Django template
I'm using Django with PostgreSQL. I have a model with a IntegerRangeField. When using {{field}} in template the result is NumericRange(2, 8, '[)') How can I get the range numbers in my template? I tried {{ field.0 }} and {{ field.1 }} but got no output. -
Productionizing Docker On AWS With Django & Postgres:
I have been stumped as of late trying to figure out a cloud environment setup that can support my 'dockerized' Python Django project. The architecture of my application is simple; I have a web service, a redis service and a database service (see my compose yml file below). My confusion is finding the correct path of moving a local setup that is stood up via the docker compose yml file to a production like environment. I absolutely love the docker compose utility and hope to use a similar config file for my production environment; however, I am finding that most container based approaches are far more complex that this... This guide has been my favorite so far, but it doesn't dive into databases and other depended on components (which leaves out the necessary nitty gritty!). Questions: Should I move away from trying to use docker-compose on a production environment? Should I use a database that is not containerized? If I shouldn't, how do I configure the containerized web service to an Amazon RDS instance? Should I break apart my docker-compose.yml into individual docker files? Should I write script to start these containers to stand up the environment? Is there a … -
Not able to link a static web page using reverse_lazy
I have written some code to develop a social media site. In that, I wanted to redirect to homepage look-a-like which i have created. I tried to create a url for this page, but there is no use. I am getting the error like: NoReverseMatch at /accounts/signup/ Reverse for 'start' not found. 'start' is not a valid view function or pattern name. Request Method: GET Request URL: http://127.0.0.1:8000/accounts/signup/ Django Version: 1.11.7 Exception Type: NoReverseMatch Exception Value: Reverse for 'start' not found. 'start' is not a valid view function or pattern name. In this project, there are three apps. Among them, "accounts" is one app. In accounts, I have created the templates folder with three files.("login.html,signup.html and start.html"). The views.py file for this : from django.contrib.auth import login, logout from django.core.urlresolvers import reverse_lazy from django.views.generic import CreateView from . import forms from django.views.generic import TemplateView class MyView(TemplateView): template_name = 'accounts/start.html' class SignUp(CreateView): form_class = forms.UserCreateForm success_url = reverse_lazy("start") template_name = "accounts/signup.html" And the urls.py file is: from django.conf.urls import url from django.contrib.auth import views as auth_views from . import views app_name = 'accounts' urlpatterns = [ url(r"login/$", auth_views.LoginView.as_view(template_name="accounts/login.html"),name='login'), url(r"logout/$", auth_views.LogoutView.as_view(), name="logout"), url(r"signup/$", views.SignUp.as_view(), name="signup"), url(r"start/$", views.MyView.as_view(), name="start") ] How to redirect … -
Uploading files to django through ajax
I'm having trouble trying to upload files to django using ajax. The upload process is done in a modal. Form <div class="modal fade bs-example-modal-lg" id="fileUploadModal" role="dialog" aria-hidden="true"> <div class="modal-dialog modal-lg"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span> </button> <h4 class="modal-title" id="myModalLabel2">Upload File</h4> </div> <div class="modal-body"> <div class="modal-body"> {% crispy fileform %} </div> </div> </div> </div> </div> The modal toggle <a data-toggle="modal" href="#fileUploadModal" data-id="0" role="button" class="btn btn-success btn-sm pull-right"> <i class="fa fa-fw fa-cloud-upload"></i> Upload File </a> This is how my file upload looks like $(document).ready(function(){ var file = 0; $('#fileUploadModal').on('show.bs.modal', function(e) { file = $(e.relatedTarget).data('id'); var form = $(e.currentTarget).find('form'); $.ajax({ url: "{% url 'employee:ajax-file-upload' %}", type: "POST", data: $(form).serialize() + '&action=load&eid=' + employee + '&fid=' + file, success: function(data) { if (data['form_html']) { $(form).html(data['form_html']); $('.datepicker').datetimepicker({ format: 'YYYY-MM-DD' }); } } }); }); $(".container" ).on('click', '#submit-file-upload', function(e) { e.preventDefault(); e.stopImmediatePropagation(); var form = $(this).closest('form'); $.ajax({ url: "{% url 'employee:ajax-file-upload' %}", type: "POST", data: $(form).serialize() + '&eid=' + employee + '&fid=' + file, success: function(data) { if (!(data['success'])) { $(form).replaceWith(data['form_html']); $('.datepicker').datetimepicker({ format: 'YYYY-MM-DD' }); } else { location.reload(); } } }); }); }); And my view looks like this @json_view @login_required def ajax_file_upload(request): if request.method == 'POST': action = request.POST.get('action') … -
How to open and read file from request.FILES without saving it to disk
Is there a way to treat a file in request.FILES same as a disk file? I want to do something like this: with open(file_in_request, 'rb') as file: #read data from that file Only, I don't want to have to save it to disk first. I will be encrypting that file and save the encrypted file to disk instead. -
Java script is not working through Handlebar- Python Django
I am a django and python beginner. Django Application is hosted in apache webserver as daemon. I am facing the issue with rendering the URL in django using java script. In my handlebar(html template), i changed did html changes, but, unfortunately changes have not been reflected. Flow be like, When calling and URL from browser, my urls.py will call views.py, inside the views.py , Node_edit.html will be renderred. Node_edit.html will contains handlebar. Sorry for my poor english. views.py @csrf_protect def hierarchyNode_new(request, parentNode_id=None): parentNodeObject = None if(parentNode_id): context = { "parentNode_id": parentNode_id } return render(request, 'test/Node_edit.html', context) Node_edit.html {% load staticfiles %} var assetList = [ //applying the html template { url: '{% static "test/handlebar/Node.handlebar" %}', loadHandler: templateLoaderFunction, name: 'Node_edit' }, ] $(document).ready( function () { debug.log("load complete") registerHandlebarHelpers() // create templates hash if not already present Handlebars.templates = Handlebars.templates || {}; console.log(assetList); chainLoadAssets(assetList, function() { var hierarchyNodeEditor = new HierarchyNodeEditor( "{% url 'test:index' %}", "{% url 'test:Node_list' %}", {% if Node %} "{% url 'test:Node_jsonbase' %}", {% else %} "{% url 'test:Node_new' %}", {% endif %} "{{ Node.id }}", "{{ parentNode_id }}", "{{ csrf_token }}" ) NodeEditor.start() }) }) </script> Node.handlebar <div class="col-sm-7"> <input type="checkbox" id="Node_edit_display" checked="checked" (Trying to make …