Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to parse list of lists in django template?
{% for repo in repo_info %} {% for branch in branch_info[forloop.counter] %} <li>Branch Name --> {{ branch }}</li> {% endfor %} {% endfor %} branch_info is a list of lists. It gives me error that could not parse the remainder on this ---> branch_info[forloop.counter] Is there any way to parse over the list elements which are also a list? -
How to organize models.py for multiple databases in Django
I am new to django, and I have to move an existing project to Django. I am using MySQL databases which I need to import as Django Models. Importing is simple with django's inspectdb. Problem is I have multiple schemas(not sure if its multiple db, or multiple schema, basically I connect to a host and inside it are multiple schema/databases inside which there are multiple tables each). Right now, all the classes are created in a massive single my-django-app/models.py file. I am not sure if this is the right way to do it, or something like my-django-app/database-1/models.py, my-django-app/database-2/models.py should be done? Looking for some guidance and best practices in django large scale apps structuring. -
Many to Many table in Django not working
My models.py contains a model that contains two foreign keys: class TestcaseHasCategory(models.Model): testcase_idtestcase = models.ForeignKey(Testcase, models.DO_NOTHING, db_column='Testcase_idTestcase') # Field name made lowercase. Category_idCategory = models.ForeignKey(Category, models.DO_NOTHING, db_column='Category_idCategory') # Field name made lowercase. class Meta: managed = False db_table = 'testcase_has_category' unique_together = (('testcase_idtestcase', 'Category_idCategory'),) In Django shell printing the objects of that table gives me this output: >>> TestcaseHasCategory.objects.all() Traceback (most recent call last): File "<console>", line 1, in <module> File "c:\Python27\lib\site-packages\django\db\models\query.py", line 232, in _ _repr__ data = list(self[:REPR_OUTPUT_SIZE + 1]) File "c:\Python27\lib\site-packages\django\db\models\query.py", line 256, in _ _iter__ self._fetch_all() File "c:\Python27\lib\site-packages\django\db\models\query.py", line 1087, in _fetch_all self._result_cache = list(self.iterator()) File "c:\Python27\lib\site-packages\django\db\models\query.py", line 54, in __ iter__ results = compiler.execute_sql() File "c:\Python27\lib\site-packages\django\db\models\sql\compiler.py", line 83 5, in execute_sql cursor.execute(sql, params) File "c:\Python27\lib\site-packages\django\db\backends\utils.py", line 79, in execute return super(CursorDebugWrapper, self).execute(sql, params) File "c:\Python27\lib\site-packages\django\db\backends\utils.py", line 64, in execute return self.cursor.execute(sql, params) File "c:\Python27\lib\site-packages\django\db\utils.py", line 94, in __exit__ six.reraise(dj_exc_type, dj_exc_value, traceback) File "c:\Python27\lib\site-packages\django\db\backends\utils.py", line 64, in execute return self.cursor.execute(sql, params) File "c:\Python27\lib\site-packages\django\db\backends\mysql\base.py", line 11 0, in execute return self.cursor.execute(query, args) File "c:\Python27\lib\site-packages\MySQLdb\cursors.py", line 202, in execute self.errorhandler(self, exc, value) File "c:\Python27\lib\site-packages\MySQLdb\connections.py", line 36, in defau lterrorhandler raise errorclass, errorvalue OperationalError: (1054, "Unknown column 'testcase_has_category.id' in 'fiel d list'") My other models are printable, only the … -
error in index.html of django-admin using django-admin-notifications
I am using django to make a new admin panel and iam also using django-admin-notifications to show notifications in my admin panel. I don't know why it is not working Here is my models.py from __future__ import unicode_literals from django.db import models class MyAlbum(models.Model): title = models.CharField(max_length=30) photos = models.IntegerField() def __unicode__(self): return self.title class Person(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) def __unicode__(self): return self.first_name class Musician(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) instrument = models.CharField(max_length=100) def __unicode__(self): return self.first_name my admin.py from django.contrib import admin from django.contrib.admin import AdminSite from .models import Person,MyAlbum,Musician from django.contrib import admin class MyAdminSite(AdminSite): site_header = 'Wedding Administration' site_admin = MyAdminSite(name='weddingadmin') admin.site.register(Person) admin.site.register(MyAlbum) admin.site.register(Musician) site_admin.register(Person) site_admin.register(MyAlbum) my notifications.py import admin_notifications from models import Person def notification(): broken_links = Person.objects.filter(status=False).count() if broken_links: return "You have %s broken link%s.<br>You can view or fix them using the <a href='/admin/linkcheck/'>Link Manager</a>." % (broken_links, "s" if broken_links>1 else "") else: return '' admin_notifications.register(notification) I have also made changes in index.html of admin site {% load notification_tag %} {% extends "admin/base_site.html" %} {% load i18n static %} {% block extrastyle %}{{ block.super }}<link rel="stylesheet" type="text/css" href="{% static "admin/css/dashboard.css" %}" />{% endblock %} {% block coltype %}colMS{% endblock %} {% … -
Java EE vs. PHP vs. Python (Django framework) [on hold]
I have a choice problem between these 3 languages. They can all get to the objective but i'm sure they have advantages and disadvantages. I've been reading all over forums that the language does not matter, it's the usage that matters. So my question is, which of these 3 languages is preferable for the development of a professional web application? NB: I am a newbie in Python and Java EE -
Celery class based tasks with CELERY_BEAT_SCHEDULE
I am wondering what is the correct approach here, and cannot find any data about this while googling: Assuming I have the class: class OkPayPaymentChecker(BasePaymentChecker): pass in 'nexchnage/tasks.py' what would be the correct CELERY_BEAT_SCHEDULE entry for this task? is it: CELERY_BEAT_SCHEDULE = { 'check_okpay_payments': { 'task': 'nexchange.tasks.OkPayPaymentChecker', 'schedule': timedelta(seconds=60), }, } Or should create an instance with it first? -
Django runserver not loading - no errors, site copied from Git to dev enviroment
Ive recently attempted to migrate to using GIT as opposed to editing my live site all the time. i have a local copy of the DB and have cloned the repo to my dev machine. there are no errors when i runserver and the port is listening, however the page never loads, is there anything else i need to check or do to get this up? runserver [root@localhost it-app]# python manage.py runserver 0.0.0.0:8000 Performing system checks... System check identified no issues (0 silenced). January 24, 2017 - 08:49:04 Django version 1.10.5, using settings 'infternal.settings' Starting development server at http://0.0.0.0:8000/ Quit the server with CONTROL-C. nmap [root@localhost ~]# sudo nmap -sT -O localhost Starting Nmap 6.40 ( http://nmap.org ) at 2017-01-24 00:45 PST Nmap scan report for localhost (127.0.0.1) Host is up (0.00043s latency). Other addresses for localhost (not scanned): 127.0.0.1 Not shown: 997 closed ports PORT STATE SERVICE 22/tcp open ssh 25/tcp open smtp 8000/tcp open http-alt Device type: general purpose Running: Linux 3.X OS CPE: cpe:/o:linux:linux_kernel:3 OS details: Linux 3.7 - 3.9 Network Distance: 0 hops OS detection performed. Please report any incorrect results at http://nmap.org/submit/ . Nmap done: 1 IP address (1 host up) scanned in 1.69 seconds … -
Django request GET parameter value list
I want to do some sorting and what I have mind is doing a GET request with a parameter named ordering like this and the value will be the model atttribute that I will use to sort like this: ?order=['-age', 'height'] the problem is when I try to receive the order parameter.. The value is a list. I tried using the ast like this: if 'order' in request.GET: import ast order = ast.literal_eval(request.GET.get('order')) queryset = queryset.order_by(*order) It worked. However, I would like to avoid using the ast library, is there any other way around? UPDATE I did my parameter like this: ?order=-age,height And just used split in python like this: if 'order' in request.GET: order = request.GET.get('order').split(',') queryset = queryset.order_by(*order) -
Django Haystack: whoosh.index.IndexVersionError: Can't read format -111
Setting up django 1.7 with haystack 2.0.0 and whoosh 2.4.0 when I run python manage.py rebuild_index get this error: Removing all documents from your index because you said so. Traceback (most recent call last): File "manage.py", line 11, in <module> execute_from_command_line(sys.argv) File "/home/ubuntu/webapps/djangoenv/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 385, in execute_from_command_line utility.execute() ... File "/home/ubuntu/webapps/djangoenv/local/lib/python2.7/site-packages/whoosh/filedb/filestore.py", line 54, in open_index return FileIndex(storage, schema=schema, indexname=indexname) File "/home/ubuntu/webapps/djangoenv/local/lib/python2.7/site-packages/whoosh/filedb/fileindex.py", line 220, in __init__ TOC.read(self.storage, self.indexname, schema=self._schema) File "/home/ubuntu/webapps/djangoenv/local/lib/python2.7/site-packages/whoosh/filedb/fileindex.py", line 113, in read raise IndexVersionError("Can't read format %s" % version, version) whoosh.index.IndexVersionError: Can't read format -111 The folder whoosh_index exists. -
Django order by via custom method
My custom method is actually a calculation and I am trying to avoid ordering via manager and if possible just use order_by. Is there a way or a one line syntax to achieve this? Here is my model: class Bet(models.Model): provider = models.ForeignKey(Provider) member = models.ForeignKey(Member) game = models.ForeignKey(Game) status = models.ForeignKey(Status) bet_id = models.CharField(max_length=200) bet_time = models.DateTimeField() bet_amount = models.FloatField() valid_bet_amount = models.FloatField() settlement_amount = models.FloatField() def get_profit(self): return self.settlement_amount - self.valid_bet_amount -
Stock & Varient Management in Python Django
I am using django1.9 & python 2.7 please suggest me good way to manage inventory, stock & versions of the product. I have some existing code that generate Invoice I only need to manage the Product Stock, Product Version and Purchase. Thank you -
How to add extra parameters to html tag from base django
lets say i have a html tag as follows in my base.html. <html lang="en-us" "some other properties"> I am extending that template to another template i want in that extended template head to be as <html lang="en" data-ng-app="app" "some other properties"> how can i achive the same in django using block statements? -
where should I find redis.conf file in django project
I have the same problem as this question says. redis does not allow me to do anything. everything was okay I don't know what happened ... even I can not set password through redis client command line. anyone can help me ? -
Model field level permission and Field value level permission in Django and DRF
I am doing a project which require some user to access (view) a model's field but they cannot update the field. Is there a way to do this? This will not be used in the admin site. Also, I want to provide permissions based on a model's field value. Is there a way to do this? Thank you! -
Django cannot translate javascript string
My LOCALE_PATHS seeting in settings.py is as follow: LOCALE_PATHS = ( os.path.join(BASE_DIR, 'locale'), ) And my locale folder is located like this: myproject locale And my urls.py py is as follow: js_info_dict = { 'packages': ('locale',), } urlpatterns = patterns('', url(r'^jsi18n/$', javascript_catalog, js_info_dict, name='javascript-catalog'), Javascript catlog script is succesfully loaded using: <script type="text/javascript" src="{% url 'javascript-catalog' %}"></script> but, string with gettext is not registered in po file: gettext('hello'); What am I mistaken here -
the django + nginx can't load staticfiles
recently when i use the { %load staticfiles % } in my django app.i just found that it shows like this picture as follows: enter image description here 。the settings files are like this: STATIC_DIR = os.path.join(BASE_DIR,'static') STATIC_URL = '/static/' STATICFILES_DIRS = [STATIC_DIR, ] STATIC_ROOT = os.path.join(BASE_DIR, "static/") and the file's directory are like follows: web1->web1->settings.py we1->static->img->ocen.jpg the base.html are like this: <!DOCTYPE html> { % load staticfiles % } <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> <img src="{ % static "img/ocen.jpg" % }" alt="show picture"> </body> </html> the ngix configure file are like this: location /static/ { alias /home/yumo/web1; } To find the reason ,I try as follows:first , i konck :domainname/static/img/ocen.jpg in the browser. I can see my ocen.jpg in the browser. second: i just create the django app in my local virtual machine without using uwsgi and nginx. i can use the { % load staticfiles %} normally to achieve my aims. i just sincerely wan't someone give me some useful advise,thank you! -
Django Testing - TypeError: argument of type model is not iterable
I'm getting an error when running python manage.py test: TypeError: argument of type 'Course' is not iterable Here are my tests: def test_course_list_view(self): resp = self.client.get(reverse('courses:list')) self.assertEqual(resp.status_code, 200) self.assertIn(self.course, resp.context['courses']) self.assertIn(self.course2, resp.context['courses']) def test_course_detail_view(self): resp = self.client.get(reverse('courses:detail', args=[self.course.pk])) self.assertEqual(resp.status_code, 200) self.assertIn(self.course, resp.context['course']) Here is my view that I'm testing: def course_list(request): courses = Course.objects.all() return render(request, 'courses/course_list.html', {'courses': courses}) def course_detail(request, pk): course = get_object_or_404(Course, pk=pk) return render(request, 'courses/course_detail.html', {'course': course}) Confused because i'm not getting an error in test_course_list_view but test_course_detail_view does throw an error? -
Get logged in users details and group permissions in rest api
In my python rest api application, I have successfully included the django oauth2 toolkit and I am getting accesstoken while logging in. Now I have to write an api to get the details of the current logged in user and his group information and the group permissions. My urls.py url(r'me', get_me), My serialzers.py class UserGroupSerializer(serializers.ModelSerializer): permissions = serializers.SerializerMethodField(required=False) groups = serializers.SerializerMethodField(required=False) def get_groups(self, obj): group_list = [] for group in obj.groups.all(): group_list.append(group.name) return group_list def get_permissions(self, obj): permissions = [] for group in obj.groups.all(): group_permissions = group.permissions.all().values_list('codename', flat=True) for group_permission in group_permissions: permissions.append(group_permission) return permissions class Meta: model = get_user_model() exclude = ('password','user_permissions',) #fields = '__all__' My views.py def get_me(request): user = request.user return { 'user': UserGroupSerializer(user).data, } When I call this api, I am getting the following error, The view account.views.get_me didn't return an HttpResponse object. It returned None instead. What is the issue? Is it the correct method am following? -
How to create HTML comboboxes which depend on each other?
I am roughly new to web development, and I believe this is a front-end question. I have a database where Makes, Models, and Years are related. I would like to create a dynamic type-in/dropdown list where: User Types-in/selects and the list filters in real time their available options using an HTML5 combobox (Search: "A" List: 'Acura, Alfa Romero') For every character a user types in or selects (from the dropdown) a 'Make' from the Makes list, Models and Years lists are filtered by the primary key (PK) of the 'Make' (these tables are related with foreign keys, and connecting tables (join tables ?) Repeat this for Models, and Years For Example... A user selects 'Acura', 'ILX', 'MDX', etc. are the ONLY available options in the Models list, and filters the Years list as well. Another user decides to skip Makes list, and goes straight to Model list and selects 'ILX', the Makes list should automatically select the appropriate 'Make' (in this case Acura.) I am using Django as a backend, in case that info was necessary. -
No output on a django python server using mysqldb
I've been following this tutorial:https://www.youtube.com/watch?v=bRnm8f6Wavk to work on creating a basic dynamic website I've create a table on the mysql server. But it doesn't seem to be showing on my website. The views.py file has the following code: from django.shortcuts import render_to_response from blog.models import posts def home(request): entries = posts.objects.all()[:10] return render_to_response('index.html',{'posts' : entries}) The models.py file has the following code from __future__import unicode_literals from django.db import models class posts(models.Model): author = model.CharField(max_length = 30) title = models.Charfield(max_length = 100) bodyText = models.TextField() timestamp = models.DateTimeField() The settings.py has the following database for input: DATABASES = { 'default': { #'ENGINE': 'django.db.backends.sqlite3', #'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), 'ENGINE': 'django.db.backends.mysql', 'NAME': 'Firstblog', 'USER': 'root', 'PASSWORD': '3305', 'HOST': '', 'PORT': '', }} I have edited the header to say : Firstblog </h1> {% for entry in entries %} {{entry.title}} <h3> Posted on {{ entry.timestamp }} by {{entry.author}} </h3> <p>{{entry.body}}</p> Following the tutorial steps, I'm stuck since there are no errors and no output either. Anything would help. Thanks! Im using anaconda to run my python at 2.7.12 using Django 1.10** -
Isotope, Infinite Scrolling, Masonry and Django
I have a masonry gallery put together with gamma gallery and I am trying to figure out how to integrate isotope filtering and infinite scrolling. I've been searching for some tutorials but I came up short. Can someone please point me to a simple example of all 3 working together? What's the right way to initialize them? Thank you -
Configure SocketServer to work with Django
I have a device that communicates with TCP port. It came with an desktop application which only runs in windows. but I want to use it in a linux server and with a django app. I tried to communicate with SocketServer library and it works fine but i'm having problem using djangos ORM in socket server. I need to store the data to database. -
Django Weasyprint on Elastic Beanstalk - Could not load GDK-Pixbuf
I've installed weasyprint on Elastic Beanstalk. The printing of html templates is working so far but im not able to print svg images. Weasyprint throws the following error: Failed to load image at "https://myurl/media/X247QAQ2IO.svg" (Could not load GDK-Pixbuf. PNG and SVG are the only image formats available.) Do I need gdk-pixbuf to print SVGs? And if so how can I install it on Amazon Linux? Yum does not have gdk-pixbuf2 available for installation -
Implementing a view callback in Django 1.10
I have a URL - it will be sending me back JSON at intervals it chooses. I want to pick up these objects on my server. How do I write the callback function and where do I put it? -
Ajax GET data returning 'None'
Here's my ajax function: $('a.username').on('click', function() { var username = $(this).html(); var url = window.location.href.split('?')[0]; $.ajax({ type: 'GET', url: url, data: { username_clicked: username, csrfmiddlewaretoken: $("input[name='csrfmiddlewaretoken']").val() }, success: function (data) { console.log(data.username_clicked) } }) }); And template: <h3><a href="{% url 'raise_profile' %}" class="username">{{ i.author }}</a></h3> url url(r'^raise_profile/', raise_profile, name='raise_profile'), and view: def raise_profile(request): if request.method == 'GET': print('get') #prints 'get' username_clicked = request.GET.get('username_clicked') print(username_clicked) #prints 'None' return render(request, 'article.html', {}) The console.log(data.username_clicked) doesn't log anything. But if I take away the {% url 'raise_profile' %} in the template, then it logs the correct data. Any reason what the problem is?