Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Celery task initiated by Django not running
In one of the POST API in Django view, I have the following: data_processing.apply_async( args=[data], queue='image', countdown=10 ) In the celery task, I have: @shared_task def data_processing(data): dataid = data['dataid'] print "ABSBBSBBB" print "ANSNNDNDN" There is no error during POSTing of data, but the print statements are not working. Nothing is getting printed on the console, but data POSTing is successful. Any help would be much appreciated!!! -
Is there an equivalent to Django manage.py commands in .NET?
I need to execute some custom operation on my database during the development process(import data from XML or other files for example), and I would know if exist something similiar to Django manage.py commands in .NET, in particular I work with Asp.NET MVC and Entity Framework 6 https://docs.djangoproject.com/en/1.10/howto/custom-management-commands/ -
https to http redirect not working in nginx configuration using rewrite
To distribute load and implement security in our application we have taken elastic Load Balancer from amazon and SSL is configured on it.Now the redirection from http to https is not working in nginx configuration on server or instances which is attached on ELB. Here is following nginx configuration:- server { listen 80 default_server; listen [::]:80 default_server ipv6only=on; server_name new.example.com; access_log /var/log/nginx/domain-access.log; location / { proxy_read_timeout 90; proxy_connect_timeout 90; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_pass http://127.0.0.1:8000; } } Firstly the server is not supporting https URLs then I add some proxy settings in confi guration but now issue is that redirection is not working i have used the following commands in ngnix configuration to redirect http to https :- 1.server{ return 301 https://$server_name$request_uri; } 2.server { rewrite ^(.*) https://$host$1 permanent; } Application deployed on server is build using django framework. -
How to create a Django superuser if it doesn't exist non-interactively?
I want to automate creation of Django users via a Bash script. I found this snippet which almost suits my needs: echo "from django.contrib.auth.models import User; User.objects.create_superuser('admin', 'admin@example.com', 'pass')" |\ python manage.py shell How can I modify it so that it's a nop if the user already exists? -
Serve protected media files with django
I'd like Django to serve some media files (e.g. user-uploaded files) only for logged-in users. Since my site is quite low-traffic, I think I will keep things simple and do not use django-sendfile to tell Nginx when to serve a file. Instead I'll let Django/Gunicorn do the job. To me this seems a lot simpler and for a low traffic site this maybe more secure. But what is the best way to organize the file storage location? Media files are all stored below MEDIA_ROOT and this directory is served by Nginx in production. If I upload my files to MEDIA_ROOT/protected/ I have to tell Nginx not to serve the files in the subdirectory protected. But is this a good idea? It seems a litte risky to me to allow Nginx access /media/ in the first place and then protect the subdirectory /media/protected/. Wouldn't it be better not to use a subdirectory of MEDIA_ROOT to store protected files? But if I try something like this quick-and-dirty in my model: upload_to='../protected/documents/%Y/%m/' Django complains: SuspiciousFileOperation at /admin/core/document/add/ The joined path (/home/me/projects/project/protected/documents/2016/09/test.file) is located outside of the base path component (/home/me/projects/project/media) So I thing it is not good practice to "leave" the MEDIA_ROOT. What … -
Django redirecting everything to homepage
I'm stuck with a Django project, I tried to add another app called login to make a login page but for some reason the page just redirects to the homepage except for the admin page For example: 127.0.0.1:8000 will go to the homepage but 127.0.0.1:8000/login will also display the homepage even though I linked another template to it. Here is my code: main urls.py from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^', include('portal.urls')), url(r'^login/', include('login.urls')), ] login urls.py from django.conf.urls import url from . import views urlpatterns = [ url(r'^login/', views.index, name="login"), ] login views.py from django.shortcuts import render def index(request): return render(request, 'login/login.html') portal urls.py from django.conf.urls import url from . import views urlpatterns = [ url(r'^', views.index, name="portal"), ] -
How can control the items in view class queryset?
class ModelListCreateView(GetQuerysetMixin, generics.ListCreateAPIView): queryset = get_objects_for_user(self.context['request'].user, 'model.view_model') serializer_class = ModelSerializer permission_classes = (permissions.IsAuthenticated,) In the above code snippet am trying to get query only the items a given user is supposed to see. I tried queryset = get_objects_for_user(request.user, 'model.view_model') but this did not work and resulted in an error 'request' not defined. After googling and trying what I have now I get the error 'self' not defined. And am also trying to implement django-guardian on top of the other permissions. -
Why SQL-query in Postgres gives one time, but same raw query in Django gives out the same time, but without the time zone?
In Postgres do next: SELECT data,message,timestamp FROM "table" WHERE id_source='asdf'AND "timestamp" BETWEEN '2016-09-27 00:00:00.000'::timestamp AND '2016-09-27 23:59:59.000'::timestamp LIMIT 300 and get date and time row as 2016-09-27 15:03:00.759+03 At Django: with connections['db'].cursor() as cursor: cursor.execute("""SELECT data,message,timestamp FROM "table" WHERE id_source='asdf'AND "timestamp" BETWEEN '2016-09-27 00:00:00.000'::timestamp AND '2016-09-27 23:59:59.000'::timestamp LIMIT 300""") querySet = cursor.fetchall() I'm get date and time 2016-09-27 12:03:00.759+00 What's wrong? Thanks. -
Django rest framework: Response 'write' & 'writelines' methods doesn't work
I'm using Django 1.8 & Django Rest Framework 3.3.2, I faced the issue that I can't 'add content incrementally' as mentioned in the docs for HttpRequest in Django https://docs.djangoproject.com/en/1.8/ref/request-response/#usage. from rest_framework.response import Response response = Response('sometext', status=status.HTTP_200_OK) response.write(' and few more lines') response.writelines([' and few more lines again']) and in browser I get response only with 'sometext' in the body. As I checked, the drf Response is based on HttpResponse, so this methods should work... Also I tried response = Response( status=status.HTTP_200_OK), but the result is an empty body. So why calls of write & writelines have no affect? -
Django filter objects by exact position of character
I have a list of codes where each character as a meaning: i.e. code: 1) 0000.ABCD 2) 1111.CACC position: 012345678 I want' to make a search for all the codes with A at position 5. 1) 0000.ABCD So the research should return only the first code. I've looked at django look_up functions but this isn't the case neither for an iexact or an icontains. Is there a way to make a search like this? -
Passing custom parameters to formset forms
Django 1.10.1 Learning "Passing custom parameters to formset forms" ( https://docs.djangoproject.com/en/1.10/topics/forms/formsets/#passing-custom-parameters-to-formset-forms). If I do like this, I can catch user in the form. class MyArticleForm(ArticleForm): def __init__(self, user=None, *args, **kwargs): pass Well, this works. If I put breakpoint at pass, I can see that user has come to the form. And this works as well: class MyArticleForm(ArticleForm): def __init__(self, user, *args, **kwargs): pass But I can't cope with the example from documentation (which uses kwargs). The code and error are below. Could you give me a kick here? forms.py class ArticleForm(forms.Form): title = forms.CharField() pub_date = forms.DateField() user = forms.CharField() class MyArticleForm(ArticleForm): def __init__(self, *args, **kwargs): self.user = kwargs.pop('user') super(MyArticleForm, self).__init__(*args, **kwargs) views.py class General(View): template_name = "general/article.html" ArticleFormSet = formset_factory(MyArticleForm) def get_formset(self): formset = self.ArticleFormSet(form_kwargs={'user': str(self.request.user)}) return formset def get_context_data(self, formset=None): if formset: context = {'my_formset': formset} else: context = {'my_formset': self.get_formset()} return context def get(self, request): context = self.get_context_data() return render(request, self.template_name, context) The error: File "/home/michael/workspace/formsets/general/forms.py", line 15, in __init__ self.user = kwargs.pop('user') KeyError: 'user' -
"TypeError: argument must be a context" after update from Python 3.4 to 3.5
I had a working project on Python 3.4 but now that I updated to 3.5 my tests are failing with the following error: File "path/to/my/module.py", line 55, in code RawSQL("(data->>%s)::numeric", ('json_key',))) File "/home/vagrant/ve3.5/lib/python3.5/site-packages/django/db/models/query.py", line 358, in aggregate return query.get_aggregation(self.db, kwargs.keys()) File "/home/vagrant/ve3.5/lib/python3.5/site-packages/django/db/models/sql/query.py", line 464, in get_aggregation result = compiler.execute_sql(SINGLE) File "/home/vagrant/ve3.5/lib/python3.5/site-packages/django/db/models/sql/compiler.py", line 859, in execute_sql val = cursor.fetchone() File "/home/vagrant/ve3.5/lib/python3.5/site-packages/django/db/utils.py", line 102, in inner return func(*args, **kwargs) TypeError: argument must be a context The relevant piece of code seems to be this one, that does an aggregate on a JSONField: numeric_value = Foo.objects.filter( **filter_kwargs ).aggregate( value=Avg( RawSQL("(data->>%s)::numeric", ('json_key',))) )['value'] I searched online but didn't find almost anything. Does anybody have any idea what's going on? -
django It seems the view func do not work
I'm trying to write a FBV to delete a subject, but there are some problem I can't figure out. It's Django 1.7.1. Below are related codes. The model Communication: ... @models.permalink def get_delete_url(self): return 'comm_delete', [self.uuid] the URLconf: url(r'^(?P<uuid>[\w-]+)/delete/$', views.comm_delete, name='comm_delete'), the views: def comm_delete(request, uuid): obj = get_object_or_404(Communication, uuid=uuid) account = Account.objects.get(id=obj.account.id) if request.method == 'POST': obj.delete() return HttpResponseRedirect(reverse('accounts/account_detail.html', args=(account.uuid,))) return render(request, 'subject_confirm_delete.html', {'object_name': 'Communication', 'object': obj}) when I click <a class="cancel" href="{{ comm.get_delete_url }}"></a> the page move to uuid/delete/ url, the form display Communication object. If I still click the cancel button, just refresh the page and nothing changed. So how can I fix it? Help me please! -
NoReverseMatch Django, get_success_url in CreateView
iam new to django and started a blog app to train my coding skills. i create a create view in my blog app to create a post. in the create view I used the function get_success_url. I want when i create a post, that it will redirect to the blog_post_list. Here is there problem, i get the error: No Resever Match. Hope somebody can help me. I guess it has to do sth with the urlpatterns. here my code. Thanks for your help main urls.py from django.conf.urls import url, include from django.contrib import admin from blog.views import AboutPageView, ContactPageView urlpatterns = [ url(r'', include('blog.urls', namespace='posts')), url(r'^blog/', include('blog.urls', namespace='posts')), url(r'^about/$', AboutPageView.as_view(), name='about'), url(r'^contact/$', ContactPageView.as_view(), name='contact'), #admin and login url(r'^admin/', admin.site.urls), ] urls in blog app from django.conf.urls import url from .views import blog_postListView, blog_postDetailView, blog_postCreateView urlpatterns = [ url(r'^$', blog_postListView.as_view(), name='blog_post_list'), url(r'^create/', blog_postCreateView.as_view(), name='blog_post_create'), url(r'^(?P<slug>[-\w]+)$', blog_postDetailView.as_view(), name='detail'), ] views in blogapp from django.contrib.auth.decorators import login_required from django.core.urlresolvers import reverse from django.http import HttpResponse from django.views.generic import View from django.views.generic.base import TemplateView, TemplateResponseMixin, ContextMixin from django.views.generic.detail import DetailView from django.views.generic.list import ListView from django.views.generic.edit import CreateView, UpdateView, DeleteView from django.shortcuts import render from django.utils.decorators import method_decorator from .models import blog_post from .forms … -
django-channels and simple chat app
I'm trying to do simple chat application like slack. But I stuck on two things. 1) How can I get online users 2) How can I get unread messages I use Redis backend and how I understood Group represents in Redis like ZSET, channels as STRING and asgi.disconected as LIST of STRING. Before I thought if I did proper disconnect Group ZSET should be deleted but that's not a truth and it stays in Redis. I absolutely stuck with channels any thoughts are welcome. -
Django python server "Can't connect to MySQL server on '127. 0.0.1' (10061)" while it was able to connect yesterday?
My python runserver isn't able to connect to my mysql server even though my MySQL service is running and I was able to connect yesterday on this machine. My runserver error: super(Connection, self).__init__(*args, **kwargs2) django.db.utils.OperationalError: (2003, "Can't connect to MySQL server on '127. 0.0.1' (10061)") My running MySQL service: I referred to this question, and tried running the mysqld.exe from C:\Program Files\MySQL\MySQL Server 5.7\bin but I'm getting the following error: C:\Program Files\MySQL\MySQL Server 5.7\bin>mysqld.exe mysqld: Can't change dir to 'C:\Program Files\MySQL\MySQL Server 5.7\data\' (Err code: 2 - No such file or directory) 2016-09-28T07:08:08.233439Z 0 [Warning] TIMESTAMP with implicit DEFAULT value is deprecated. Please use --explicit_defaults_for_timestamp server option (see doc umentation for more details). 2016-09-28T07:08:08.233439Z 0 [Warning] Insecure configuration for --secure-file -priv: Current value does not restrict location of generated files. Consider set ting it to a valid, non-empty path. 2016-09-28T07:08:08.233439Z 0 [Note] mysqld.exe (mysqld 5.7.15) starting as proc ess 1764 ... 2016-09-28T07:08:08.236439Z 0 [Warning] Can't create test file C:\Program Files\ MySQL\MySQL Server 5.7\data\abc-PC.lower-test 2016-09-28T07:08:08.236439Z 0 [Warning] Can't create test file C:\Program Files\ MySQL\MySQL Server 5.7\data\abc-PC.lower-test 2016-09-28T07:08:08.238439Z 0 [ERROR] failed to set datadir to C:\Program Files\ MySQL\MySQL Server 5.7\data\ 2016-09-28T07:08:08.238439Z 0 [ERROR] Aborting 2016-09-28T07:08:08.239439Z 0 [Note] Binlog end 2016-09-28T07:08:08.239439Z 0 [Note] … -
How to retrieve all data blocks from database at a certain entry in Django?
I am very sorry for this newbie question... I have data stored in the database (mysql) as tuples. These data look like (datetime, frequency, current) ... etc. How to retrieve all data from database at a certain time? for example, I want to get all the saved data at "2015-9-9 8:23:10" -
django-pyodbc-azure. Invalid object name 'django_session'
I need help with setting up my project. I used django-pyodbc-azure and I have this in my settings.DATABASES: DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc','NAME': 'DBNAME','USER': 'USER', 'PASSWORD': 'PASSWORD', 'HOST': '10.xx.xx.xx,1433', 'OPTIONS': { 'driver': 'SQL Server Native Client 10.0', }, }, } Sorry I don't know how to format the code above. I don' know the problem is, but it returns an error: ProgrammingError: ('42S02', "[42S02] [Microsoft][SQL Server Native Client 10.0][ SQL Server]Invalid object name 'django_session'. (208) (SQLExecDirectW); [42000] [Microsoft][SQL Server Native Client 10.0][SQL Server]Statement(s) could not be prepared. (8180)") How do I fix this? -
heroku-django-uploaded image is not displayed if DEBUG=False
I deployed my Django app on heroku. Every thing is working fine except displaying images. Any uploaded image is not displayed if DEBUG=False. settings.py DEBUG = False ALLOWED_HOSTS = ['salma-blog.herokuapp.com'] STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage' STATIC_ROOT = os.path.dirname(myblog.__file__)+'/static/' STATIC_URL = '/static/' #upload images MEDIA_ROOT= os.path.dirname(myblog.__file__)+'/static/myblog/images' MEDIA_URL='/images/' urls.py urlpatterns=[ ... ]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) image tag in my template <img alt="img" src="/blog{{image}}"></a> -
SyntaxError: invalid syntax when installing graphite
I installed the following: Graphite,Carbon,Whisper : 0.9.15,Django: 1.5,Python:2.6.6 under the Centos 6.7. After started Httpd successfully, the same error occured in the file: error.log. why and how to fixed it, I appreciate your help. Thanks. [Tue Sep 27 16:08:38 2016] [error] warn('SECRET_KEY is set to an unsafe default. This should be set in local_settings.py for better security') [Tue Sep 27 16:08:38 2016] [error] [client ::1] mod_wsgi (pid=2761): Exception occurred processing WSGI script '/opt/graphite/conf/graphite.wsgi'. [Tue Sep 27 16:08:38 2016] [error] [client ::1] Traceback (most recent call last): [Tue Sep 27 16:08:38 2016] [error] [client ::1] File "/usr/lib/python2.6/site-packages/django/core/handlers/wsgi.py", line 255, in call [Tue Sep 27 16:08:38 2016] [error] [client ::1] response = self.get_response(request) [Tue Sep 27 16:08:38 2016] [error] [client ::1] File "/usr/lib/python2.6/site-packages/django/core/handlers/base.py", line 178, in get_response [Tue Sep 27 16:08:38 2016] [error] [client ::1] response = self.handle_uncaught_exception(request, resolver, sys.exc_info()) [Tue Sep 27 16:08:38 2016] [error] [client ::1] File "/usr/lib/python2.6/site-packages/django/core/handlers/base.py", line 220, in handle_uncaught_exception [Tue Sep 27 16:08:38 2016] [error] [client ::1] if resolver.urlconf_module is None: [Tue Sep 27 16:08:38 2016] [error] [client ::1] File "/usr/lib/python2.6/site-packages/django/core/urlresolvers.py", line 342, in urlconf_module [Tue Sep 27 16:08:38 2016] [error] [client ::1] self.urlconf_module = import_module(self.urlconf_name) [Tue Sep 27 16:08:38 2016] [error] [client ::1] File "/usr/lib/python2.6/site-packages/django/utils/importlib.py", line … -
Column as alias is ambigous in Postgresql
I am migrating the database from MySQL to Postgrsql. In MySQL I create a view like this: create or replace view translated_attributes_with_attribute_templatevalues as select concat_ws('', translated_attributevalues.attribute_id, translated_attributevalues.languagecode, attribute_template_value.id ) AS id, ... GROUP BY id But in Postgrsql I got the message: column reference "id" is ambiguous LINE 1: ...GROUP BY id How can I use the alias "id"? I renamed it, but than other parts of the code break, because it assumes the column is named id. -
Django insert default data after migrations
I want my application to have default data such as user types. Whats the most efficient way to manage default data after migrations. it needs to handle situations such as after i add a new table it adds the default data for it. -
How to measure the time profile of each django test?
I'd like to measure the (wall?) time each individual test case takes to run. I suppose wrapping the test_runner in a timeit will do the job, but before I dive down that rabbit hole perhaps there is a smarter way to do it? This already gives me a cProfile to pore over, but nothing really jumps out as horrendously bad. I'm thinking perhaps my time can be focused on the ones that run the longest. time python -m cProfile -o keep-p4-serialize.profile manage.py test -v 3 -k --parallel 4 eg: test_dependencies (api.tests.TestMetricClasses) ... ok (4.003s) test_metrics (api.tests.TestMetricClasses) ... ok (8.329s) test_parameters (api.tests.TestMetricClasses) ... ok (0.001s) -
Followup : missing required Charfield in django Modelform is saved as empty string and do not raise an error
If I try to save incomplete model instance in Django 1.10, I would expect Django to raise an error. It does not seem to be the case. models.py: from django.db import models class Essai(models.Model): ch1 = models.CharField(max_length=100, blank=False) ch2 = models.CharField(max_length=100, blank=False) So I have two fields not allowed to be empty (default behavior, NOT NULL restriction is applied by Django at MySQL table creation). I expect Django to rase an error if one of the fields is not set before storing. However, when I create an incomplete instance, the data is stored just fine: >>> from test.models import Essai >>> bouh = Essai() >>> bouh.ch1 = "some content for ch1" >>> bouh.save() >>> bouh.id 9 >>> bouh.ch1 'some content for ch1' >>> bouh.ch2 '' >>> I would have expected Django to raise an error. If I force ch2 to None, however, it raises an error: >>> bouh = Essai() >>> bouh.ch1 = "some content for ch1" >>> bouh.ch2 = None >>> bouh.save() Traceback (most recent call last): (...) return Database.Cursor.execute(self, query, params) django.db.utils.IntegrityError: NOT NULL constraint failed: test_essai.ch2 >>> bouh.id >>> bouh.ch1 'some content for ch1' >>> bouh.ch2 >>> Explanation: Django is not raising an error as default behavior … -
Django: why does reverse of OneToOne return a tuple?
I have a OneToOne field in my model: class Portfolio(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, primary_key=True, on_delete=models.CASCADE) elsewhere in a view, I am trying to get the Portfolio from a User portfolio = request.user.portfolio My debugger shows the result as this: <class 'tuple'>: (<Portfolio: 9999999>,) Why is it doing this? Shouldn't 1 to 1 return a single object?