Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Access to Django settings using Redis
I have a project on Heroku. I just recently added Redis for job queueing through Heroku's add-ons feature. I've followed Heroku's simple tutorial to get things up and running. I call the function like so: result = q.enqueue(some_other_class.some_function, some_argument) In some_function there is a call to a variable from the Django's settings file. I follow the normal procedure, which works without Redis: from django.conf import settings and then get the variable settings.THE_VARIABLE. When I use Redis though, that doesn't work. I get the error: ImproperlyConfigured: Requested setting THE_VARIABLE, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings The DJANGO_SETTINGS_MODULE variable is set. Does the worker not have access to Django settings? If so, how can I get around this? -
django channels behind https
Django-channels websocket was working well on a AWS server until I installed letsencript ssl. I tried another certificate but the wss is not working. I saw this online deployment that shows that channels can work behind https: https://django-channels-example.herokuapp.com/ I followed andrewgodwin sugestions here: https://github.com/django/channels/issues/248 I pointed daphne to port 8000: daphne -b 0.0.0.0 vp.asgi:channel_layer --port 8000 -v 2 And I used the same port in my javascript: chatsock = new WebSocket( ws_scheme + '://' + window.location.host + ":8000/chat" ); My nginx config: server { listen 80; server_name mysite.com www.example.com; return 301 https://www.example.com$request_uri; } server{ listen 443 ssl; server_name mysite.com www.example.com; ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem; root /home/ubuntu/vp; access_log /var/log/nginx/guni-access.log; error_log /var/log/nginx/guni-error.log info; location /wss/ { proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-for $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_pass http://0.0.0.0:8000; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; } location / { proxy_pass http://0.0.0.0:8000; proxy_set_header HOST $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-for $remote_addr; proxy_set_header X-Forwarded-Proto $scheme; port_in_redirect off; proxy_connect_timeout 300; } location ~ /.well-known { allow all; } location /static/ { alias /home/ubuntu/vp/static/; expires 30d; } } My browser tells that: Firefox can’t establish a connection to the server at wss://example.com:8000/chat. Any suggestions? Thanks. -
Django wsgi.py Http 404 error
I m new to Django, and presently using it for my company app. I m using wsgi to start off (required for the API). The index.html is able to load the js and css files, but when clicking on get 'Run' on the html, it gives an error code of 404. --> GET/CurrentTime HTTP/1.1 404 in App.py: from App import wsgi app = wsgi.application in wsgi.py: import os os.environ['DJANGO_SETTINGS_MODULE'] = 'App.settings' from django.core.wsgi import get_wsgi_application application = get_wsgi_application() in urls.py: urlpatterns = [ url(r'^CurrentTime$', TestControllers.get_current_time), ... in TestControllers.py def get_current_time(req): return HttpResponse(datetime.now().strftime("%a, %d %B %Y %I:%M:%S%p")) Can someone help? Appreciate it. -
Django Checkbox checked / uncheck with rules
Given a Django form with some fields: class FruitsForm(forms.Form): fruit_choices = forms.TypedMultipleChoiceField("Fruits I Like", required=True, widget=forms.CheckboxSelectMultiple()) name = forms.CharField(required=True, max_length=20) I have a bunch of 3 fruits - Apple, Orange and Pear. When the form is loaded, however, I want only Apple to be pre-selected / pre-checked. I know that to make a checkbox checked, use the attrs={'checked' : 'checked'} dictionary but how do I do it at a more granular level? In other words, I would like the form to look: Name: [Text Field] Fruits I Like: Apple [X] Fruits I Like: Orange [ ] Fruits I Like: Pear [ ] -
Django models's attributes correctly saved by forms, but returns None type when queried
I have a model called UserProfile defined like so: class UserProfile(models.Model): user = models.OneToOneField(User) website = models.URLField(blank=True, null=True) location = models.CharField(max_length=200, null=True) longitude = models.FloatField(null=True) latitude = models.FloatField(null=True) credit = models.FloatField(default=0, null=True) def __unicode__(self): return self.user.username The 'register' page includes the following form: When it is submitted it goes to: def register(request): registered = False if request.method == "POST": user_form = UserForm(request.POST) profile_form = UserProfileForm(request.POST) if user_form.is_valid() and profile_form.is_valid(): print(request.POST) lat = request.POST.get('lat') print("lat is: " + lat) lng = request.POST.get('lng') user = user_form.save() user.set_password(user.password) user.save() profile = profile_form.save(commit=False) profile.user = user profile.latitude = lat profile.longitude = lng profile.save() else: print user_form.errors, profile_form.errors else: profile_form = UserProfileForm() user_form = UserForm() return render(request, "register.html", {'user_form' : user_form, 'profile_form' : profile_form}) That all seems to work fine, but when I try to query this data in another view, the location, lat, and lng properties come up as 'None' types. def link(request): print("trying to authenticate...") if request.user.is_authenticated(): user_profile = UserProfile(user=request.user) else: return render(request, 'login.html') if request.method == "POST": print("request was a post.") if request.is_ajax(): print("request is ajax.") print("User profile is: " + str(user_profile)) # returns billy, so we're looking at the right object print("user location is: " + str(user_profile.location)) user_longitude = user_profile.longitude user_latitude … -
How should I handle user uploaded media in django?
This has been a really hard nut for me to crack, so I'm posting here in hopes of getting some insight. I'm developing an application which lets the user upload images and audio. I'm really stumped on how I should approach saving and retrieving these files in my API however. First off: I have to make sure that the files are seperated in folders and not in one big folder to avoid performance issues. Which means I also need to have my API know how to retrieve these files. I have googled and googled to no avail. I know that I should not use django itself for serving and saving files, so what should I use instead? And how should I have django communicating with said thing? On top of that, my files are actually being processed (images) so, there might even be some performance bottlenecks if people decide to upload really big content. What type of server should I use for serving files, maybe a python based server? I'm sorry if this is a stupid question, I've just had a really hard time figuring out how to structure this kind of thing, but I hope I've explained myself good … -
Using < in django template
I have a newbie question. I've been recently trying out Django, and I notice that if I ever write a template tag of the sort: {% if some_var < 10 %} the < symbol is highlighted in sublime almost as if it's a syntax error (or warning). Now of course it works correctly, but I'm wondering why this highlighting occurs in the first place. Do some browsers have difficulty parsing < when reading HTML code or something? Please enlighten me (and > doesn't get highlighted to make matters worse!). I'm actually considering writing a custom template tag that performs the "is less than" comparison. -
Reverse accessor clashes in Django
Error : 1) user.Login.password: (fields.E304) Reverse accessor for 'Login.password' clashes with reverse accessor for 'Login.username'. 2) user.Login.username: (fields.E304) Reverse accessor for 'Login.username' clashes with reverse accessor for 'Login.password'. models.py from django.db import models from django.core.urlresolvers import reverse class User(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) username = models.CharField(max_length=100) password = models.CharField(max_length=50) confirm_password = models.CharField(max_length=50) email = models.EmailField(max_length=100) position = models.CharField(max_length=50) def get_absolute_url(self): return reverse('user:register', kwargs={'pk': self.pk}) class Login(models.Model): username = models.ForeignKey(User, on_delete=models.CASCADE) password = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): login = {'username': self.username, 'password': self.password} return login -
DRF(django-rest-framework) and TokenAuthentication, how to set author based Token?
settings.py REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.TokenAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.AllowAny', ), } serializers.py class UserSerializer(serializers.ModelSerializer): related_postwriter = serializers.PrimaryKeyRelatedField(many=True, read_only=True) class Meta: model = User fields = ('id', 'username', 'email', 'related_postwriter') class PostSerializer(serializers.ModelSerializer): class Meta: model = Post fields = ('id', 'created_date', 'author', 'text', 'image') def create(self, validated_data): validated_data['author'] = self.context['request'].user return super(PostSerializer, self).create(validated_data) models.py class Post(models.Model): author = models.ForeignKey(User, related_name='related_postwriter') text = models.TextField(blank = False) image = models.ImageField(null = False, blank = False, upload_to='images') created_date = models.DateTimeField( default=timezone.now ) def __str__(self): # __unicode__ on Python 2 return self.text views.py class PostViewSet(viewsets.ModelViewSet): serializer_class = PostSerializer permission_classes = [IsAuthenticated] queryset = Post.objects.all() I had to make this RESTful api for json request and json response. When i use this RESTful api for Android application, I learned that i login and get Token from RESTful api, and then that Token is used to post data to RESTful api through Header. As postman capture, I must fill "author":"number" on Body. I think this number means that user's registering order on my RESTful api. From above capture, that author is first user of my RESTful api. How can i fill "author" part automatically using Token (or other way not using Token)? How can i … -
Django heroku uploading files
[Errno 30] Read-only file system: '/static_in_env' I am new to heroku, i have been developing python/Django application and it is running well on my local computer, but when i push it to heroku i can not get all my static files, and i can't upload files on live app as i can in my local computer! Any idea! here is the error! OSError at /admin/products/product/add/ [Errno 30] Read-only file system: '/static_in_env' Request Method: POST Request URL: https://asidecom.herokuapp.com/admin/products/product/add/ Django Version: 1.8 Exception Type: OSError Exception Value: [Errno 30] Read-only file system: '/static_in_env' Exception Location: /app/.heroku/python/lib/python2.7/os.py in makedirs, line 157 Python Executable: /app/.heroku/python/bin/python Python Version: 2.7.12 Python Path: ['/app', '/app/.heroku/python/bin', '/app', '/app/.heroku/python/lib/python27.zip', '/app/.heroku/python/lib/python2.7', '/app/.heroku/python/lib/python2.7/plat-linux2', '/app/.heroku/python/lib/python2.7/lib-tk', '/app/.heroku/python/lib/python2.7/lib-old', '/app/.heroku/python/lib/python2.7/lib-dynload', '/app/.heroku/python/lib/python2.7/site-packages', '/app/.heroku/python/lib/python2.7/site-packages/setuptools-25.2.0-py2.7.egg', '/app/.heroku/python/lib/python2.7/site-packages/pip-8.1.2-py2.7.egg'] Server time: Sat, 10 Sep 2016 10:14:54 +0000 -
Django: Saving to database connundrun
I have the following within my view which works perfectly: if request.method == 'POST': form = SelectTwoTeams(request.POST,user=request.user) if form.is_valid(): teamSelection1 = UserSelection(campaignno = 102501350, teamselection1or2 = 1, teamselectionid_id = request.POST['team1'], user_id=currentUserID, fixturematchday=fixturematchday, soccerseason_id=soccerseason) teamSelection1.save() teamSelection2 = UserSelection(campaignno = 102501350, teamselection1or2 = 2, teamselectionid_id = request.POST['team2'], user_id=currentUserID, fixturematchday=fixturematchday, soccerseason_id=soccerseason) teamSelection2.save() When the code is run it ends up nicely in my database as it should: mysql> select * from straightred_userselection; +-----------------+------------+-------------------+-----------------+---------+-----------------+----------------+ | userselectionid | campaignno | teamselection1or2 | teamselectionid | user_id | fixturematchday | soccerseasonid | +-----------------+------------+-------------------+-----------------+---------+-----------------+----------------+ | 9 | 102501350 | 1 | 6 | 349 | 2 | 1025 | | 10 | 102501350 | 2 | 7 | 349 | 2 | 1025 | +-----------------+------------+-------------------+-----------------+---------+-----------------+----------------+ 2 rows in set (0.00 sec) However, lets just say I now want to choose two different teams (currently 6 & 7 under the teamselectionid column). I can select them in my form and update but when the code is run it just adds another two rows to the table rather than update the current ones. The check to see if it needs to be a new set of team selections of an update is simply if: fixturematchday and soccerseasonid are then same … -
Django+Raw Sql Query: See raw sql query running behind Django ORM in get method
Trying to see the SQL query running behind each Django ORM. For this I am doing: item = Item.objects.filter(Id=81771130003051321541).query Here I am using filter to get multiple fetch.Above query gives me the desired output. Now the problem starts, when I am trying to use get API item = Item.objects.get(Id=81771130003051321541).query It fetches a single record then trying to see the raw SQL query running behind Django ORM then It displays like: AttributeError: 'Item' object has no attribute 'query' Doesn't Django support to see the Raw SQL query for get API? May be I am wrong.Can someone share some idea? -
WSGI module and Django settings locations
I'm using Django with uWSGI and trying to organise my web server config files as follow: /proj/ web_config/ docker-compose.py ... prod/ nginx.conf wsgi.py uwsgi_params uwsgi.ini ... app/ __init__.py settings.py My problem is I don't know how to reference the final django settings module from my WSGI module: /proj/web_config/prod/uwsgi.ini [uwsgi] # ... module = wsgi env = DJANGO_SETTINGS_MODULE=(../../)app.settings # <- Problem here Is there a way to point to the right app.settings without placing uwsgi in a parent directory ? -
Manually set models.DateTimeField
I've created a Transaction table which I want to test, one of the most important field of this table is: models.DateTimeField( default=timezone.now) In order to test my app with the database, I need historical data. Currently when I create a transaction, it sets the date and time automatically, so it is always current. I need previous month data and I'm wondering if I can manually set the above field when I create a transaction? -
invalid request block size 21573
I was reading the tutorial provided in http://uwsgi-docs.readthedocs.io/en/latest/tutorials/Django_and_nginx.html This very tutorial is a great tutorial. I have been able to configure django server on my raspberry pi raspbian system, on my Ubuntu Desktop too. Now I am trying to do the same on a Virtual Machine, Ubuntu 16.04, nginx server. On the line, uwsgi --socket :8001 --wsgi-file test.py I get an error saying invalid request block size 21573 on the terminal I went through the uwsgi tutorial that said not to use --http for --socket; Either way I have not been able to get my webserver running. Please help. Nginx is currently serving a wordpress site on start. -
How to handle Django request handler hanging
On a webpage I have a button which makes ajax request, on server side a library function is called, DB updated and page is reloaded on call success. If network connection is lost during library call it hangs inifinitly. I want to terminate and restart the call on a subsequent button presses. What happens in framework in case of hanging handler? Should I run a separate thread/process and terminate it if needed? In the latter case how to pass call results to the page, after the process is done? -
How to add permission to a class to access another class fields in Djnago(1.10)?
Imagine that i have class named Product, and it here is the code: class Product(models.Model): serial = models.CharField(max_length=30) ... ... Now i have my Adminclass that inherit from User. I want that my objects from admin class has access to Product.serial(field) while other users dose not have. I want something like this: class Admin(User): name = models.CharField(max_length=30) ... class Meta: self.addPermission(Product.serial) I dont want to use Custom Permissions of Django . Can we just add some functionality to these permissions rather than just 0 or 1 ? -
multi column search in django using ajax
I am working on a listing in django project. The scenario is that When i click on FAQ listing page then it redirects me to the listings where i get all faq. Now i have to search using different keywords. There is total five keywords through which i can search for particular results. Code is questions = Help.objects.all().filter().values('id','question','description','status','created','modified').order_by('-id') if 'question' in ajax_data: #add filter for question if 'description' in ajax_data: #add filter for description if 'status' in ajax_data: #add filter for status if 'created' in ajax_data: #add filter for created if 'modified' in ajax_data: #add filter for modified questions = Help.objects.all().filter(#add all conditions here dynamically after applying filters).values('id','question','description','status','created','modified').order_by('-id') First when page refresh it executes first query which returns all data, now using ajax filters have to be applied, i have done all ajax code just want logic of this search. Search should perform like if i enter question only it should filter according to question, but if i search using question, status and created filed it should apply filter for all these three keywords. -
Django Database - Complete Reset
This morning I have had a complete meltdown with my django progect :( I have been fiddling with models and then got an error. Cut a long story short I am now in a mess and absolutely nothing works. The good news is that the content of the database is only test data so can all be lost. I did a search on stackoverflow and found the following link: Django 1.8: Create initial migrations for existing schema Below is a list of all my migration folders: meta\migrations straightred\migrations allauth\account\migrations allauth\socialaccount\migrations allauth\socialaccount\providers\openid\migrations That all makes sense but I do have 2 quick questions: 1) Do I remove the migrations for the project alluth? (a social network login app) 2) The allauth app also has some directories named: south_migrations. Should these also be deleted? Many thanks in advance, any help would be appreciated as I am now staring at a couple of months work not running because of a database hiccup :( -
Django : Aggregate Sum works on view only after a refresh
I have an Invoice model in Django that has multiple Line models.(line items that have a title, unit price , and qty) I have a 'addline' view that allows to add item lines to the invoice. The view also displays all current invoice lines and a calculated sum of the total price for all line items. when I submit a new line item, the view refreshes to the same page and the line item appears properly, but the total (totalservices or totalgoods) of line items is not updated . It becomes updated when i refresh the page manually , or when i add another line -with the previous line total. here is my relevant view def addline(request, id): form = AddLineForm(request.POST or None ) invoice = get_object_or_404(Invoice, id = id) linelist = Line.objects.filter(invoice = id).order_by('created_at') servicelines = linelist.filter(line_type = "S") goodslines = linelist.filter(line_type = "G") totalservice = servicelines.aggregate(Sum('line_total'))['line_total__sum'] print servicelines.aggregate(Sum('line_total')) totalgoods = goodslines.aggregate(Sum('line_total'))['line_total__sum'] if form.is_valid(): instance = form.save(commit=False) #do schtuff with data instance.invoice = invoice instance.line_total = instance.unit_price *instance.qty #print instance.line_total if form.cleaned_data.get('overwrite'): invoice.invoiced_service = totalservice or 0 #or zero to prevent fuss if list is empty invoice.invoiced_goods = totalgoods or 0 invoice.save() form.save() form = AddLineForm() return redirect('invoice_detail', id) … -
How to configure Atom to autocomplete Django templates
I need to find a way/package to make Atom use autocomplete for Django projects, especially Django templates. I found this package in Atom's installer, but it doesn't include a shortcut for auto completion of this syntax {% %}, {{ }} which I need the most. Any help will be appreciated -
celery task is not firing up
I am using celery with django. my tasks are like this: @periodic_task(run_every=crontab(minute='*/10')) def sending_report(): frequencies = ['4', 'daily', 'weekly'] today = datetime.today() for frequency in frequencies: report = SendReport(frequency, datalist=[]) report.send_report() del report @periodic_task(run_every=crontab(minute=0, hour='11,15,19')) def sending_html_report(): cpm = HtmlMailer('11,15,19') cpm.send_report() del cpm @periodic_task(run_every=crontab(minute=0, hour='10')) def sending_tat_report(): cpm = HtmlMailer('10') cpm.send_report() del cpm the first task running every 10 minutes work but the other tasks at fixed time are not executing. i even tried @periodic_task(run_every=crontab(hour=10, minute=0)) too but this decorator din' helped as well. I am running celery with this command: celery -A reportMailer worker -B -l info I f i run with celeryd -B -l info, it shows no tasks but with previous command it correctly displayed the three tasks. Do i have to install something called celerybeat, could not find any package by that name though ? Please help me figure a way out.Thanks. -
Django: filter a queryset based on a 3 step foreign key connection
I have a bunch of models, related through the user model:settings.AUTH_USER_MODEL Model 1: class Submission(models.Model): ... user = models.ForeignKey(settings.AUTH_USER_MODEL) Model 2: class Block(models.Model): ... current_teacher = models.ForeignKey(settings.AUTH_USER_MODEL) Model 3: class CourseStudent(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL) block = models.ForeignKey(Block) ... Given a User teacher, how can I get a query set of Submissions, where: (apologies, I'm struggling with how to best describe this) CourseStudent.user = Submission.user CourseStudent.block is one of the Blocks that has current_teacher=teacher In other words: teachers teach specific Blocks, students have courses in those blocks. Students submit work. Teachers only want to see work submitted by students in their (the teacher's) block. -
Calculate max value of object field after model save
In views.py I have this class CarListView(ListView): model = Car def get_context_data(self, **kwargs): context = super(CarListView, self).get_context_data(**kwargs) context['max_price'] = Car.objects.all().aggregate(Max('price')) return context Aggregate method will be called every time user requests the page. This will add some delay to page loading. I want this max_price variable to be calculated every time admin saved new Car objects. How to do this? -
Get number of tweets per min for perticular channel
I am using pypi Twitter API I need to call twitter API to get tweets of one channel after certain interval. I need tweet counts in that time period. For ex. @NASA channel tweet counts of it every 5 mins. I am looking at search tweets . Is this correct? But it does not give tweets count I think.