Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Web audio player takes time to play a song
I have made a basic online music player in django. When I ran it on the localhost, the response was fast when I clicked on any song or clicked the next/prev button. I have deployed it on pythonanywhere and the response is so slow. I think it takes time to first download the song from the server. But when I see other online music player, their response is so fast. What can be done to make response time for my app fast? The songs are stored in the database as a file and the files are stored in the media section. Here is the link to the music player: online music player -
Django SlugField pretty SEO URL
I want to create SEO friendly product URLS:- Following is my url:- url(r'^ad/(?P<slug>[-\w\d]+),(?P<pk>\d+)/$', (views.AdDetail.as_view()), name='item_detail'), My views:- class AdDetail(View): template_name = 'ads/ad_detail.html' def get(self, request, slug, pk, *args, **kwargs): ad = AdDetailAPI.get_ad(pk) return render(request, self.template_name, ctx) My templates:- <a href="{% url 'item_detail' slug=item.slug pk=item.id %}"> This is where the problem lies, it says NoReverseMatch Reverse for 'item_detail' with arguments '()' and keyword arguments '{u'pk': 47L, u'slug': ''}' not found. 2 pattern(s) tried: [u'ad/(?P<slug>[-\\w\\d]+),(?P<pk>\\d+)\\.(?P<format>[a-z0-9]+)/?$', 'ad/(?P<slug>[-\\w\\d]+),(?P<pk>\\d+)/$'] Where does the problem exactly lies? Also, when I browse to /ad/abcd,46 or /ad/pqr,46, as expected it shows the content of object 46. But the browser url gets change to /ad/pqr,46 from /ad/abcd,46. What I want is that the irrespective of whatever slugfield is typed into the browser address, the address bar should show the actual title slugfield assigned. -
Django dynamic query in model manager
Im having a problem where i use the same code over and over again (to save an item, than an item transaction for that item). So i thought maybe i need a Model Manager which will help me with this, and im not very experienced in django, so i would like to know how do you handle this kind of problems. My idea was to create a InventoryManager like: class InventoryManager(models.Manager): def create_item(self, **kwargs): # def create_item_trans(self, item, **kwargs): pass def create_item_with_trans(self, **kwargs): # create item # create item_trans # return item with item_trans But in the create_item_with_trans, i dont have a way to send the kwargs, cause **create_item acceps different kwargs, and create_item_transaction accepts different **kwargs -
Is Django using design patterns internally?
I would like to know if the implementation of Django framework is using some design patterns internally. So far I have been able to identify Iterator, Factory design patterns. Thanks for help. -
can i send a message to a django template in an HttpResponseBadRequest?
Can i send an error message attached to an HttpResponseBadRequest which will be displayed in my template? ie. view.py def myView(): .... return HttpResponseBadRequest(msg) template.html $.get(url,function(data){ ... }) .done(function(){ ... }) .fail(function(){ alert(msg); }) -
Django Allauth include signup in different form
I'm using django 1.9.7 and django-allauth to handle my user authentication. I have a contact form that includes several Fields (including the users email address) which are saved as a model in the backend, from there I am using a ModelForm to display the fields. So far so good. Now there should be a checkbox, which when checked should add two fields (password, password confirm) and instantly create an account with the email and password provided. For this I would probably manually create a user object from the view that receives the contact information, but since its security relevant I'm wondering if there is an easy way to call a allauth method from python that creates the user (or even provides the form). How would I go about this? -
Django: how to exclude instances in other model's relationship?
I have two models: Model A: field1 Model B: a_list = ForeignKey(A) Now, I want to find A not in the list of B's a_list, like: A.objects.exclude(self__in=b.a_list) How can I do this? -
csrf_token not found django ajax
<script> function post(e) { data = $("#form_add_post").serialize(); $.post( "/post/", function( data ) { alert("posted"); }); return false; } function addPost(){ $(".matter").html("<form id='form_add_post' onsubmit='return post(event);'>{% csrf_token %} <table> <tr> <td class='heading'>Title: </td> <td class='box'><input type='text' name='title'></td> </tr> <tr> <td colspan='2'><textarea class='data' name='content'></textarea></td> </tr> </table> <input id='submitt1' type='submit'> </form>"); } </script> I am trying to perform a AJAX post call. I have placed the csrf_token too. I have cross checked the data that is being sent. It is showing the entire details including the csrf_token. My data: csrfmiddlewaretoken=foYqu9LrR25AomOmcFkaEicmN3CU2wcRNVg1gRPgl2F9XfL6IWerpbSK6TUKd4Ke&title=Tester&content=hhgj%3B%3Bhghjbjn But i am getting a 403 error showing CSRF verification failed. Request aborted. -
Cassandra "Unable to connect to any servers" via Django, while sqlsh works
I have cassandra 3.x on my linux machine. I try to connect to it with https://github.com/tschellenbach/Stream-Framework from stream_framework.feeds.cassandra import CassandraFeed I can connect to cassandra from command line cqlsh' and usingDBeaver GUI` on port 9042. When i try to run Django with above import i get error: cassandra.cluster.NoHostAvailable: ('Unable to connect to any servers', {'::1': error(111, "Tried connecting to [('::1', 9042, 0, 0)]. Last error: Connection refused"), '127.0.0.1': error(111, "Tried connecting to [('127.0.0.1', 9042)]. Last error: Connection refused")}) I've looke round for solution and changed in /etc/cassandra/cassandra.yaml to: rpc_address: 0.0.0.0 #from localhost rpc_port: 9042 #from 9160 listen_address: 127.0.0.1 #from localhost but it didn't helped. How can i solve it? -
Getting javascript array from django json dumped dictionary
I have a json-dump data from Django view - {"7": {"1": 0, "2": 0, "3": 0, "4": 0, "5": 0, "6": 0, "7": 0, "8": 0, "9": 0, "10": 0, "11": 1, "12": 0}} I need an array in javascript from the json data like - var list = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0] Also I need the key "7". No jQuery but javascript What is the best way? -
Type error while creating new logic adapter chatterbot
I am making a new logic adapter in my chatterbot-django project following documentation from https://chatterbot.readthedocs.io/en/stable/adapters/create-a-logic-adapter.html. when i run runserver command, it throws TypeError following is my adapter code: from chatterbot.adapters.logic import LogicAdapter from chatterbot.conversation import Statement import wikipedia class WikiAdapter(LogicAdapter): def __init__(self, **kwargs): super(WikiAdapter, self).__init__(kwargs) def can_process(self, statement): print(statement) if statement.text.startswith("#wiki"): return True return False def process(self, statement): request=statement.text[6:] confidence=1 response=Statement(wikipedia.summary(request,sentences=3)) return confidence,response if i comment out the super command, no error is thrown. I dont know why it is working. Can anyone pls explain me -
explaining pgbouncer log entries in django project
I'm using pgbouncer in a Django web app of mine. The application server and the database server are two separate VMs. pgbouncer is installed on the application server. Pertinent settings in pgbouncer.ini are: [databases] dbname = host=80.211.128.113 port=5432 dbname=dbname pool_mode = transaction max_client_conn = 250 default_pool_size = 100 Once pgbouncer took over, I checked pgbouncer.log and found lots of entries as follows: 2016-11-15 12:26:27.514 582 LOG S-0x1192740: dbname/myuser@80.211.128.113:5432 new connection to server 2016-11-15 12:26:27.517 582 LOG C-0x11afcb8: dbname/myuser@127.0.0.1:42262 login attempt: db=dbname user=myuser 2016-11-15 12:26:27.523 582 LOG S-0x1192a10: dbname/myuser@80.211.128.113:5432 new connection to server 2016-11-15 12:26:27.528 582 LOG C-0x11af880: dbname/myuser@127.0.0.1:42250 closing because: client close request (age=0) 2016-11-15 12:26:27.528 582 LOG S-0x1191a98: dbname/myuser@80.211.128.113:5432 closing because: unclean server (age=0) 2016-11-15 12:26:27.548 582 LOG C-0x11afb50: dbname/myuser@127.0.0.1:42258 closing because: client close request (age=0) 2016-11-15 12:26:27.556 582 LOG C-0x11aff88: dbname/myuser@127.0.0.1:42256 closing because: client close request (age=0) 2016-11-15 12:26:27.556 582 LOG S-0x1191c00: dbname/myuser@80.211.128.113:5432 closing because: unclean server (age=0) 2016-11-15 12:26:27.564 582 LOG C-0x11aff88: dbname/myuser@127.0.0.1:42264 login attempt: db=dbname user=myuser 2016-11-15 12:26:27.569 582 LOG C-0x11afb50: dbname/myuser@127.0.0.1:42265 login attempt: db=dbname user=myuser 2016-11-15 12:26:27.570 582 LOG S-0x1191c00: dbname/myuser@80.211.128.113:5432 new connection to server 2016-11-15 12:26:27.593 582 LOG C-0x11af448: dbname/myuser@127.0.0.1:42255 closing because: client close request (age=0) 2016-11-15 12:26:27.593 582 LOG C-0x11afcb8: dbname/myuser@127.0.0.1:42262 closing because: … -
Django - relational constraint (constraint on user's groups)
In my django - app I setup permissions for different facilities with the following groups: ADMIN_<facility> USER_<facility> Where admin has all the rights that user has and some more. I would like to constraint that a user that has the group ADMIN_facility1 will never be added to group USER_facility1. My approach: class MyUser(models.Model): ... @property def admin_facilities(self): [g.name for g in self.groups.filter(name__startswith="ADMIN_")] @property def user_facilities(self): [g.name for g in self.groups.filter(name__startswith="USER_")] def save(self, **kwargs): for user_fac in self.user_facilities: if user_fac in self.admin_facilities: # remove the user facility self.groups.remove( self.groups.get(name="USER_{}".format(user_fac) ) super(MyUser, self).save(**kwargs) ... This approach does not work, as the groups are not there yet during the call of the save function. Question: How do I constraint that a user who is in a ADMIN_<facility> group can never be added to the according USER_<facility> group? -
How to render custom widgets for date and time in django forms.DateTimeField
So I have a model with DateTimeField and a form (not ModelForm, just forms.Form) with DateField and TimeField which I combine in order to get datetime for my model. I want to change this form to ModelForm. In order to do that, I need to unite them. It's a bit hard to explain but here's a part of my template where I have this form: <div> <input type="date" class="datepicker" name="{{form.rent_start_date.name}}" value="{{form.rent_start_date.value}}"> {{form.rent_start_date.label_tag}} </div> <div> <select name="{{form.rent_start_time.name}}"> {% if form.rent_start_time.value %} <option value="" disabled>Time</option> {% else %} <option value="" disabled selected>Time</option> {% endif %} {% for time in times %} {% if time == form.rent_start_time.value %} <option value="{{ time }}" selected>{{ time }}</option> {% else %} <option value="{{ time }}">{{ time }}</option> {% endif %} {% endfor %} </select> <label>{{form.rent_start_time.label}}</label> </div> Here I access form.rent_start_date.name to get name for input that will contain date part and .value to get its value same thing with form.rent_start_time.name and .value to get input name and its value for time counterpart Two inputs correspond to two fields in my form class. I want them both to correspond to a single form field, namely forms.DateTimeField How can I modify this so I have two separated inputs … -
Django-CMS Unpublished page still navigable
I have 3 sites with Django-CMS sharing the same database and code but in different folders (the SITE_ID conf changes from folder to folder). They were suppose to have translations in en but for now we just want to show the pt pages so I unpublished all en pages. In my first site it works ok but in the other the en pages are visible in the published site instead of redirecting to the correspondent pt page as it happens in the first site. I tried to add to settings: CMS_PAGE_CACHE = False But still got the same problem. Also I checked and all the sites have the last svn commit and they have the pt language as the default one. Do you know what could be happening? Thanks :) -
Syntax error javascript django trans
i am getting a syntax error at the line $('#email').val({% trans 'Enter your Email' %}); it says SyntaxError: missing ) after argument list what seems to be the issue? -
Merging an SQLalchemy query with a django queryset in the django admin
I would like to display some extra columns in a Django admin changelist, but unfortunately due to it being a legacy system the only way to get these is by using sqlalchemy. I don't want to perform a query for each item in the change list for these extra columns, therefore I need to get the data, save it somewhere, and use this when popluating the columns (i.e. program(), stage()) I have managed to get this working by using the following code but I have a feeling what I am doing is very very wrong because I'm saving the sqlalchemy data onto the Admin view itself: class WaitingAdmin(BookingAdmin): list_display = ('school', 'program', 'stage') def school(self, obj): return obj.source def program(self, obj): d = self.dic.get(obj.user_profile.student_number) return d['program'].strip() if d else '' def stage(self, obj): d = self.dic.get(obj.user_profile.student_number) return d['stage'] if d else '' def get_queryset(self, request): # evaluate the queryset to get the student ids queryset = super(WaitingAdmin, self).get_queryset(request).get_admin_queryset(user=request.user) student_ids = filter(None, queryset.values_list('user_profile__student_number', flat=True)) # get other data based on ids in query session = user_data_session() data = getCurrentRegStatusExtendedList(session, student_ids) # save a dict on the View self.dic = {d[0].student_id: {'stage': d[1].stage_text, 'program': d[2].programme_title, } for d in data} return queryset … -
There is no South database module 'south.db.sqlite3' for your database
I have inherited a django web app and apparently it uses south so I installed it on the vir-env running the application and added one line for the SOUTH_DATABASE_ADAPTERS in settings.py but when I run the server from command line I get the below error message which I googled so much and couldn't figure it out. SOUTH_DATABASE_ADAPTERS = { 'default': 'south.db.sqlite3' } Server error (env) root@mike-VirtualBox:/var/www/CordeliaHanelBackend-master# python manage.py runserver Performing system checks... /var/www/CordeliaHanelBackend-master/StudioHanel/urls.py:7: RemovedInDjango110Warning: django.conf.urls.patterns() is deprecated and will be removed in Django 1.10. Update your urlpatterns to be a list of django.conf.urls.url() instances instead. url(r'^contact/', views.contact, name='contact'), /var/www/CordeliaHanelBackend-master/CordeliaHanelBackend/urls.py:31: RemovedInDjango110Warning: django.conf.urls.patterns() is deprecated and will be removed in Django 1.10. Update your urlpatterns to be a list of django.conf.urls.url() instances instead. url(r'^', include('StudioHanel.urls', namespace='StudioHanel')), System check identified no issues (0 silenced). There is no South database module 'south.db.sqlite3' for your database. Please either choose a supported database, check for SOUTH_DATABASE_ADAPTER[S] settings, or remove South from INSTALLED_APPS. -
simple loop in rendered template django cms plugin
I want to loop data taken from database in rendered template. Using cms plugin. I dont have problem looping data in html template. But if i use CMSPlugin to insert new app in placeholder, nothing shows. If i run url localhost:port/test.html.I got input what i want. But rendered template doesnt loop data. {% for post in posts %} {% post.firstoption %} {% endfor } if I use code below, nothing shows in my rendered template. Values are passed in rendered template. Because, if i try {{instance.firstoption}} i get value shown in template. Problem is i cant loop data with tag instance. {% for post in instance.posts %} {% post.firstoption %} {% endfor } -
List all static assets in Django
Is there a way to list all static assets from views. One way is to use absolute path but is there a Django way of doing it? Another way I tried using was request.build_absolute_uri(), but os.listdir() cannot open it as it's a URL. Any suggestions? -
(Django 1.10) referring to properties of an object referred to by ForeignKey
In my app each object Kurs needs to have a field 'prowadzacy' specifying the user to which the given Kurs belongs. Therefore, my models.py has the following: class Kurs(models.Model): prowadzacy = models.ForeignKey(User) I also need to know the first name of the user in possession of the given Kurs. In shell, the following works: >>> k=Kurs.objects.get(id=1) >>> k <Kurs: Wprowadzenie do epi 2> >>> k.prowadzacy <User: leszekwronski> >>> k.prowadzacy.first_name u'Leszek' Eventually I need to have a field in my Kurs object containing an outcome of a procedure transforming the possessor's first and last names. As a first step, I want to add a field containing just the first name. However, when I modify my models.py to contain the following: class Kurs(models.Model): prowadzacy = models.ForeignKey(User) imie = prowadzacy.first_name then I get the following error: AttributeError: 'ForeignKey' object has no attribute 'first_name' I tried using 'self.prowadzacy.first_name' instead of just 'prowadzacy.first_name', but to no avail: NameError: name 'self' is not defined What am I doing wrong? After reading this I suspect that I cannot refer to the name of a field in a model until the definition of that particular model is finished. However, 1) I'm not sure and would be grateful for … -
ImportError: No module named tastypie.api
When I run Django (1.9) I get following error message "ImportError: No module named tastypie.api". Searched the previous post none were helpful (eg. here). I guess it is because I used the latest django-tastypie (django-tastypie-0.13.3). Below is the current configuration on v-env I have. Please let me know what you suggest. Regards and thanks in advance. Django (1.9) Pillow (3.4.2) pip (9.0.1) setuptools (28.8.0) wheel (0.30.0a0) (env) root@mike-VirtualBox:/var/www/CordeliaHanelBackend-master# python manage.py runserver Performing system checks... Unhandled exception in thread started by <function wrapper at 0x7fb98582dcf8> Traceback (most recent call last): File "/var/www/CordeliaHanelBackend-master/env/local/lib/python2.7/site-packages/django/utils/autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "/var/www/CordeliaHanelBackend-master/env/local/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 116, in inner_run self.check(display_num_errors=True) File "/var/www/CordeliaHanelBackend-master/env/local/lib/python2.7/site-packages/django/core/management/base.py", line 426, in check include_deployment_checks=include_deployment_checks, File "/var/www/CordeliaHanelBackend-master/env/local/lib/python2.7/site-packages/django/core/checks/registry.py", line 75, in run_checks new_errors = check(app_configs=app_configs) File "/var/www/CordeliaHanelBackend-master/env/local/lib/python2.7/site-packages/django/core/checks/urls.py", line 10, in check_url_config return check_resolver(resolver) File "/var/www/CordeliaHanelBackend-master/env/local/lib/python2.7/site-packages/django/core/checks/urls.py", line 19, in check_resolver for pattern in resolver.url_patterns: File "/var/www/CordeliaHanelBackend-master/env/local/lib/python2.7/site-packages/django/utils/functional.py", line 33, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/var/www/CordeliaHanelBackend-master/env/local/lib/python2.7/site-packages/django/core/urlresolvers.py", line 417, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/var/www/CordeliaHanelBackend-master/env/local/lib/python2.7/site-packages/django/utils/functional.py", line 33, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/var/www/CordeliaHanelBackend-master/env/local/lib/python2.7/site-packages/django/core/urlresolvers.py", line 410, in urlconf_module return import_module(self.urlconf_name) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/var/www/CordeliaHanelBackend-master/CordeliaHanelBackend/urls.py", line 8, in <module> from tastypie.api import Api ImportError: No module named … -
Nginx return 502 but not 500
I use django and nginx to offer service. when use dev environment(python manage.oy runserver) and do something wrong, it can return 500 error. however when use nginx+django and do the same, it return 502. How can I config nginx.conf to let it return 500? my config is as below: upstream veevaqa.veevaorion.com.upstream { server 60.205.56.175:8000 weight=1; } server { listen 80; server_name veevaqa.veevaorion.com; location /nginxstatus{ access_log on; auth_basic "nginxstatus"; auth_basic_user_file htpasswd; } location / { index index.jsp; proxy_pass http://veevaqa.veevaorion.com.upstream; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; client_max_body_size 10m; client_body_buffer_size 128k; proxy_connect_timeout 300; proxy_send_timeout 300; proxy_read_timeout 300; proxy_buffer_size 4k; proxy_buffers 4 32k; proxy_busy_buffers_size 64k; proxy_temp_file_write_size 64k; } } -
Django: filter out few fields from json response
First of all, I'm very new to Django world, there could be a similar question, however i did not find a satisfactory answer. Here is my scenario, i have few external REST endpoints, which I will hit from my Django app and get say 100-key JSON response. Now, when I'm writing my API in Django app, this response i'll have to trim and send it to outer world. Say for example, My API is, GET /api/profiles/1472 which will give user profile with id 1472. Now, this API will inturn call some other REST endpoint and fetch actual profile's data. So, in a way I'm writing a proxy endpoint. This proxy endpoint is supposed to trim out some fields and give it back to caller. I've not written model classes for this. What are best ways to achieve this in Django? -
High latency of API's
We are using Django + gunicorn(sync type) + Nginx + Postgres for development. Currently we log everything into same file. So there are some problems associated with this. As every gunicorn worker is writing into same file, worker is sitting idle for the time in which some other worker is writing to the file. So what happens is after some time number of requests on nginx get queued as no worker is free. So latency is added in 2 stages:- a) function latency due to logging b) latency due to busy workers. i.e requests get queued on nginx and are alloted late to workers. Can somebody help me to get the best solution in this case.