Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
python/django difference between dates and ratio for progress bar
I'm trying to make an automatic progressBar, that takes the end_date of an event and the beggining_date and gives you the ratio of completion of the event, like 20% complete or 40% complete, etc. I think there might me multiple errors in my code, but currently I'm getting an AttributeError 'QuerySet' object has no attribute 'time_progress' .The idea is to call the time_progress(), and it will return the completion ratio. My code: models.py class Event(models.Model): # other Fields above beginning_date = models.DateTimeField("Beggining date") end_date = models.DateField("Completion date") def time_progress(self): now = timezone.now() progress = ((now - self.beginning_date).days/((self.end_date - now).days + (now - self.beginning_date).days))*100 return progress views.py class EventView(generic.DetailView): model = Event template_name = 'info/event.html' def get_context_data(self, **kwargs): context = super(EventView, self).get_context_data(**kwargs) context['progress'] = Event.objects.filter(pk=self.kwargs.get('pk')).time_progress() return context event.html <div class="progress"> <div class="progress-bar progress-bar-success progress-bar-striped" role="progressbar" aria-valuenow="{{ progress }}" aria-valuemin="0" aria-valuemax="100" style="width:{{ progress }}%">{{ progress }}%</div> </div> -
Django doesn't uses memcached framework
I'm trying to find out how Django caching framework works. I set memcached in settings.py but the time of loading page didn't get smaller and Django-debug-toolbar shows 0 cache calls. This is what I've set in settings.py: CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache', 'LOCATION': '127.0.0.1:11211', } } CACHE_BACKEND = 'memcached://127.0.0.1:11211/' CACHE_MIDDLEWARE_ALIAS = "default" CACHE_MIDDLEWARE_SECONDS = 60 MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'querycount.middleware.QueryCountMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.cache.UpdateCacheMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.cache.FetchFromCacheMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'debug_toolbar.middleware.DebugToolbarMiddleware', ] Now I refreshed two times the page with a table of objects. I thought that the second time there should be no database lookups because nothing changed. What am I missing? -
Apache Notice/Error For Django Website
For the last two months, I've been seeing this set of errors in my logs. [core:notice] AH00094: Command line: '/usr/sbin/httpd -D FOREGROUND' [mpm_prefork:notice] AH00173: SIGHUP received. Attempting to restart [so:warn] AH01574: module wsgi_module is already loaded, skipping [auth_digest:notice] AH01757: generating secret for digest authentication ... [lbmethod_heartbeat:notice] AH02282: No slotmem from mod_heartmonitor [mpm_prefork:notice] AH00163: Apache/2.4.23 (Amazon) mod_wsgi/3.5 Python/3.4.3 configured -- resuming normal Once in a while, I'll also see this before the SIGHUP received line. [cgi:error] AH02811: script not found or unable to stat: /var/www/cgi-bin/php These set of notices/errors occur 1-3 times per day. I'm not very familiar with Apache, could anyone tell me what these messages mean and how I may fix the issue. Some additional information: I'm running the website with Django 1.8 using AWS Elastic Beanstalk (Amazon Linux). -
Setting up Django with Redis, Celery to send emails via Gmail
I'd like to set up my Django app to set up emails via Gmail using an async task queue. I'm using Celery, with Redis as my broker. However, I'm not able to send emails when I define Celery as my email backend -- I get an error stating that the connection failed: ...: --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) /Users/user/virtualenvs/myapp/lib/python3.4/site-packages/kombu/utils/functional.py in __call__(self) 35 try: ---> 36 return self.__value__ 37 except AttributeError: AttributeError: 'ChannelPromise' object has no attribute '__value__' During handling of the above exception, another exception occurred: ConnectionRefusedError Traceback (most recent call last) /Users/user/virtualenvs/myapp/lib/python3.4/site-packages/kombu/connection.py in _ensured(*args, **kwargs) 493 try: --> 494 return fun(*args, **kwargs) 495 except conn_errors as exc: /Users/user/virtualenvs/myapp/lib/python3.4/site-packages/kombu/messaging.py in _publish(self, body, priority, content_type, content_encoding, headers, properties, routing_key, mandatory, immediate, exchange, declare) 186 immediate, exchange, declare): --> 187 channel = self.channel 188 message = channel.prepare_message( /Users/user/virtualenvs/myapp/lib/python3.4/site-packages/kombu/messaging.py in _get_channel(self) 208 if isinstance(channel, ChannelPromise): --> 209 channel = self._channel = channel() 210 self.exchange.revive(channel) /Users/user/virtualenvs/myapp/lib/python3.4/site-packages/kombu/utils/functional.py in __call__(self) 37 except AttributeError: ---> 38 value = self.__value__ = self.__contract__() 39 return value /Users/user/virtualenvs/myapp/lib/python3.4/site-packages/kombu/messaging.py in <lambda>() 223 self.__connection__ = connection --> 224 channel = ChannelPromise(lambda: connection.default_channel) 225 if isinstance(channel, ChannelPromise): /Users/user/virtualenvs/myapp/lib/python3.4/site-packages/kombu/connection.py in default_channel(self) 818 # make sure we're still connected, and if not refresh. … -
What is wrong with the following ajax code?
I am trying to pass the id of 'this' object from ajax call to django view but i am getting the following error in my broswer : as i am beginner to both django and ajax that is why there could be errors in the code. here is my code : views.py from django.shortcuts import render from librarysystem.models import Users from django.http import JsonResponse def index(request): template = 'librarysystem/Elib.html' return render(request,template) def validateForm(request, id): data = { 'isTaken' : Users.objects.filter(username__iexact=request.GET.get(id,None)).exists(), #'emailidTaken' : Users.objects.filter(emailid__iexact=emailid).exists(), } return JsonResponse(data) urls.py from django.conf.urls import url from .import views urlpatterns = [ url(r'^registered/$',views.create_user), url(r'^$', views.index, name="Index"), url(r'^validate(?P<id>)/$',views.validateForm), #url(r'^article/$', views.Article, name="Article"), ] ajax code: <script type="text/javascript"> function validateForm() { //var emailid = $('#emailid').val() ; $.ajax({ url: '/librarysystem/validate/this.id/', data: { 'this.id': this.value, //'emailid': emailid, }, dataType: 'json', success: function(data){ if (data.isTaken){ $('#error').html(this.id + ' Already taken.').css('color','red'); }else $('#error').html(''); } }) ; } $(document).ready(function() { $('#retrypassword').keyup(checkPasswordMatch); $("#username, #emailid, #password, #retrypassword").keyup(validateForm); }); </script> thanks for your kind replies :) -
Django dropdown divider
I have a dropdown menu that i generated by looping through a list of objects. I have a divider after object 0, 10, and 13. However some user don't have access to all objects so the dividers dont show. Can someone suggest a good way have after the last object in each bucket. I.e. bucket [0], [1-10], [11-13]. They buckets are areas in different states. I'm not necessarily asking for someone to write the code for me. I'm just asking how to do this conceptually as I'm quite new to coding and Django. Any help is much appreciated! <ul class="dropdown-menu"> {% for i in area_list %} {% if not i.area_id == area.area_id %} {% if i.area_id == 0 or i.area_id == 10 or i.area_id == 13 %} <li><a href="{% url 'market_overview' area_id=i.area_id %}">{{ i.area_name }}</a></li> <li class="divider"></li> {% else %} <li><a href="{% url 'market_overview' area_id=i.area_id %}">{{ i.area_name }}</a></li> {% endif %} {% endif %} {% endfor %} </ul> -
Django session translation setting is sticky for one language, but not another?
I have a really weird problem I've never seen before. I'm using Django 1.10. I have 2 dictionary files: /locale/fr/LC_MESSAGES/django.po /locale/zh/LC_MESSAGES/django.po The application strings are written in English. The dictionary files are complete, and compiled to mo files. I store each user's language preference in the language field of the UserProfile. When updating their profile, I apply the language translation to the session. # 'up' is a UserProfile object pertaining to the user up.update(language=form.cleaned_data['language']) translation.activate(up.language) self.request.session[translation.LANGUAGE_SESSION_KEY] = up.language return super(self, UpdateUserProfile).form_valid(form) This works fine for French. The return super renders the form template in French, and then I can navigate to other pages and see French text. It doesn't work for Chinese. The return super page renders the form template in Chinese (and I've verified the language setting in the shell after saving), but then all other pages revert to English when I navigate away. I've restarted the dev server just in case it was due to old settings. It's not. What could cause this error? -
How to return multiple html pages in django views?
I want my view to open multiple pages. Can someone suggest on how to do it. Thank You -
Error: Reverse for 'home' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: []
The project name is project1 and I have one app in it - home. I'm making a navbar in the index.html. However, the first <li> tag in the index.html gives me error and I'm not sure how to fix it. home's urls.py from django.conf.urls import url from . import views app_name = 'home' urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^portfolio/$', views.portfolio, name='portfolio'), url(r'^blog/$', views.blog, name='blog'), url(r'^contact/$', views.contact, name='contact'), ] home's views.py def index(request): return render(request, 'home/index.html') home's index.html <!DOCTYPE html> <html lang="en"> <head> <title>My Website</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> {% load staticfiles %} <link rel="stylesheet" href="{% static 'home/css/bootstrap.css' %}"> <link rel="stylesheet" href="{% static 'home/css/basic.css' %}"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> </head> <body> <nav class="navbar navbar-inverse"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="#">Pranav Gupta</a> </div> <ul class="nav navbar-nav"> {% url 'home' as home %} <li {% if request.path == home %} class="active" {% endif %} ><a href="{% url 'home' %}">Home</a></li> <li><a href="#">Portfolio</a></li> <li><a href="#">Blog</a></li> <li><a href="#">Contact</a></li> </ul> </div> </nav> -
Updating which python my django app uses
The django app running on localhost in a virtualenv uses the default python version 2.7.3 that is under /usr/bin/ but I installed Python 2.7.9 under ~/.opt/bin/python2.7. I updated the $PATH but I want the django app to use the locally installed python version by default. Please help me understand how to make that happen. Thank you. -
Pdfcrowd sending parameters to html
How could I send parameters to the html before to use Pdfcrowd and print it? -
How can i pass the current object's id from ajax call to django view?
I am trying to pass the id of 'this' pointer from ajax to django view. I know how to pass it to django but i don't know how to catch this id in django view or you can say django urls.py. Here is my code so far: views.py: from django.conf.urls import url from .import views urlpatterns = [ url(r'^registered/$',views.create_user), url(r'^$', views.index, name="Index"), url(r'^validate/$',views.validateForm), # this is where i want to catch the id ] ajax code <script type="text/javascript"> function validateForm() { $.ajax({ url: '/librarysystem/validate/', data: { 'this.id': this.value, }, dataType: 'json', success: function(){ } }) ; } $(document).ready(function() { $("#username, #emailid, #password, #retrypassword").keyup(validateForm); }); -
Django Channels: delayed group message
I'm writing multiplayer online browser game and have some trouble now My consumer: @channel_session def tankAction(message): user = message.channel_session.session_key room = message.channel_session['room'] data = json.loads(rdb.get('battle-'+room)) recieve_data = json.loads(message.content['text']) if recieve_data['action'] == 'tankDestroyed': for tank in data['tanks']: if tank['id'] != recieve_data['data']: tank['score'] += 1 Group('battle-%s' % room).send({ 'text': json.dumps({ 'action': 'setScore', 'tanks': data['tanks'] }) }) data = json.dumps(data) rdb.set('battle-' + room, data) p = Process(target=startGame, args=(room, )) p.start() and function: def startGame(room): sleep(3) Group('battle-%s' % room).send({ 'text': json.dumps({ 'action': 'respawn', }) }) print ('battle-%s' % room +' respawn') But there isn't any message from server on client-side. With Django Channels.delay i don't know how to release it. I've combined in one consumer message.send and group.send - all work fine, but this thing doesn't want to do it. -
Django 1.10 single widget type for all ModelForm fields
I have a ModelForm, which is composed from Model, with huge amount of columns with very different data types. However, I need to make ModelForm whose all mentioned fields in ModelForm have the same widget type (for example, checkbox, but it may be textarea, or whatever..). ModelForm: class EntertainerCheckboxForm(forms.ModelForm): class Meta: model = Entertainer fields = ['first_name', 'second_name','last_name', ...] widgets = { 'first_name': CheckboxInput(), 'second_name': CheckboxInput(), 'last_name': CheckboxInput() ... } Is there any simple generic solution for this? I already read questions below, and were not helpful in this case: django apply widget for all fields -
Django - Using ChainedModelChoiceField (smart_selects)
I am using smart_selects in Django to filter drop down views. In my admin page, I was successful in doing this using 'ChainedForeignKey' I am now trying to create a user form and implement the same thing with 'ChainedModelChoiceField' Basically I am trying access my model data on a form so that when a user selects a 'State', only cities in that state appear. My models are already populated as well. models.py: class State(models.Model): state= models.CharField(max_length=140) def __str__(self): return self.state class City(models.Model): city= models.CharField(max_length=140,unique=True) state= models.ForeignKey(State) def __str__(self): return self.city form.py from django import forms from django.forms import ModelChoiceField, ModelForm from smart_selects.form_fields import ChainedModelChoiceField from search.models import State, City class MyForm(forms.Form): user_state = forms.ModelChoiceField(queryset = State.objects.all(),required=True) user_city=ChainedModelChoiceField( .. //html page {% block title %}Contact - {{ block.super }}{% endblock %} {% block content %} <h1>Contact</h1> <form role="form" action="" method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Submit</button> </form> {% endblock %} the 'city' drop down just appears blank. I see that the args for ChainedModelChoiceField are: self, to_app_name, to_model_name, chained_field, chained_model_field,foreign_key_app_name, foreign_key_model_name, foreign_key_field_name,show_all, auto_choose, sort=True, manager=None, initial=None, view_name=None -
Why doesn't the following ajax code work?
I am trying to get the value of currently active object and checking if that exists in the database at the background using django. ajax code and jquery: <script type="text/javascript"> function validateForm() { var username = $('#username').val() ; $.ajax({ url: '/librarysystem/validate/', data: { 'this.id': this.value, // this doesn't work //'username': username, // this works }, dataType: 'json', success: function(data){ if (data.usernameTaken){ $('#error').html('Sorry! Already taken.').css('color','red'); }else $('#error').html(''); } }) ; } } $(document).ready(function() { $("#username, #emailid, #password, #retrypassword").keyup(validateForm); }); </script> -
How to create new Building Configuration in OpenShift (for Django app)
I need to create a customized building configuration for my OpenShift(NextGen) Django application .Currently I am having django-psql-persistent configuration, which is comes with OpenShift(NextGen)-Django by default. -
Add descriptive text to the right of field in Django admin
I have a DecimalField in my model that I'd like to show up in the admin interface with a unit to the right of the field, like so: I think if I add help_text to the field, that will show up below the field. Is there a way to specify it to show up to the right? -
Relation between tables in different schemas in django with postgresql
I'm working with Django 1.9 with Postgresql and I stuck in a problem with relations between tables in different schemas. The problem that I'm facing is that I have a table, for example, named product, which is in a schema named dataflex and another table named client_product_sale_stx in another schema. When I try to migrate a relation between client_product_sale_stx and product, I got this error: Applying armazem.0077_clientproductsalestx_setor_id...Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 350, in execute_from_command_line utility.execute() File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 342, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 348, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 399, in execute output = self.handle(*args, **options) File "/usr/local/lib/python2.7/dist-packages/django/core/management/commands/migrate.py", line 200, in handle executor.migrate(targets, plan, fake=fake, fake_initial=fake_initial) File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/executor.py", line 92, in migrate self._migrate_all_forwards(plan, full_plan, fake=fake, fake_initial=fake_initial) File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/executor.py", line 121, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/executor.py", line 198, in apply_migration state = migration.apply(state, schema_editor) File "/usr/local/lib/python2.7/dist-packages/django/db/backends/base/schema.py", line 90, in __exit__ self.execute(sql) File "/usr/local/lib/python2.7/dist-packages/django/db/backends/base/schema.py", line 110, in execute cursor.execute(sql, params) File "/usr/local/lib/python2.7/dist-packages/django/db/backends/utils.py", line 79, in execute return super(CursorDebugWrapper, self).execute(sql, params) File "/usr/local/lib/python2.7/dist-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) File "/usr/local/lib/python2.7/dist-packages/django/db/utils.py", line 95, in __exit__ six.reraise(dj_exc_type, dj_exc_value, traceback) File "/usr/local/lib/python2.7/dist-packages/django/db/backends/utils.py", line 64, in … -
TemplateDoesNotExist for Django test
Everything works fine when I run site, but when I run test, I got TemplateDoesNotExist exception for file ../index.html Structure is index.html, comments(index.html). -
How to store efficiently a two-dimensional array with different File types in a Django Model (PostgresSQL)
I will like to store in a Django model the variations on the price of some houses for a date. For example: House.objects.create(name='house1', prices=[ ['27-12-2015', 200000], ['14-01-2016', 190000], ]) House.objects.create(name='house2', prices=[ ['22-04-2015', 140000], ]) Because I'm using PostgreSQL I can use a two-dimensional array with ArrayField. But I think it can't contain different type of Fields (for example date and int). I will also like to be efficient when doing queries to get the prices for all the houses between 2 dates. So my question: which is the best approach for this problem? Thank you in advance! -
running Dajngo web application publicly on the web
i'ev finished making a chatbot web application using Django and python3 and during the development phase i was using the: python3 manage.py runserver to see the results and test the application. Now i want for the application to entered like any other website publicly using URL. any recommendation for deploying the django project? thank you? -
django postgres JsonField encoding
i have JSONField in a model this field store json in 'utf8' but when i am trying to get the value of this field it is being escaped model field: details = JSONField(blank=True, default={}) database row: code : from stores.models import Item i=Item.objects.all()[0] i.details output in console and django admin: i want django to show details without escaping {u'\u0633\u064a\u0628': u'\u0634\u0633\u064a'} -
Timer object inconsistently accessible
I am starting a Python Timer in a Django view and I am using another Django view to cancel it. However, I find that I cannot access the Timer object consistently when I am trying to cancel it. The code in my "views.py" looks like this: import threading myTimer = None def f(): pass def startTimer(request): global myTimer myTimer = threading.Timer(10000, f) myTimer.start() pass def stopTimer(request): if myTimer != None: myTimer.cancel() else: print("No timer found.") pass When I try to cancel the timer, many times, I get the "No timer found." message. After some tries, seemingly in a random fashion, the Timer object is found and the cancellation succeeds. -
Adding to session dictionary
I'm trying to create a view function which updates the users cart (session) on add and removal. def shoppingCartAdd(request): data = json.loads(request.POST['post_data']) if 'shopping_cart' not in request.session: #<-- create the session dict request.session['shopping_cart'] = {} if data["action"] == "add": with open(MEDIA_ROOT + '/json/products.js', 'r') as json_file: products = json.loads(json_file.read()) #<-- json file that contains product information json_file.close() item = products["products"][data["id"]] #<-- get the item info from json #If the item is not in the session add it. Otherwise do something. if data["id"] not in request.session['shopping_cart']: request.session['shopping_cart'][data["id"]] = item else: print('Exists') #Do something else. #Remove the item from the dict. if data["action"] == "remove": request.session['shopping_cart'].pop([data["id"]], None) context = {'shoppingCart' : request.session['shopping_cart']} return JsonResponse(context) My problem is that I cannot add more than two items to my dictinary. I'm not sure what I'm doing wrong here. If I click on the first item it'll create the session and add it properly, and if I try to add it again it'll print out "exists". But if I add a second and try to add it again, it will not print out "exists" on the 2nd item. Here's a print of my session with two items. using print(request.session['shopping_cart']) { '38': {'name': 'hergh', 'price': 23, …