Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Effects on django rpy2 constantly calling caret train on incoming data
Using R's caret package to do some simple stupid machine learning. I have a train set that I've trained my model(gbm) and am calling the whole thing using rpy2. As data gets posted in, I run it against the model and get a prediction. There is a feature for the user to confirm the prediction (or multiple at a time). When a new data piece is confirmed, I want to incorporate it into the train dataset and re-run the model so it learns! I'm worried what will happen to performance if multiple users confirm different data at nearly the same time. Thoughts? -
raw query with primary key
My model class Despacho (models.Model): bus=models.ForeignKey(Bus) contador = models.IntegerField() cerrado = models.BooleanField(editable=False) class Bus(models.Model): numero_bus=models.CharField(max_length=255,unique=True) en_ruta = models.BooleanField(editable=False) I need a query to extract the data which I save a bus, and I enter a number of the bus and I need to know if there is a dispatch that matches the search try to do the following query db postgresql d = Despacho.objects.raw('''SELECT * FROM operaciones_despacho WHERE operaciones_despacho.bus = '%s' AND operaciones_despacho.cerrado = '%s' ;'''%(bus.numero_bus,False)) error : column operaciones_despacho.bus does not exist -
Django 1.10 - makemigrations command not detecting changes for unmanaged models
Thanks in advance for your help. Inside mi project I have an app involving models that were generated from an existing database. As those tables are administered by a DBA, they are kept as unmanaged models. As it is possible that we require to re-generate the models from db due to changes in the schema, we have created alternative proxy models for each of those models to decouple the part that we manage from what we don't. Below you can see an example based on our current layout. The example shows a generated model with a FK to another generated model, accordingly the proxy model has a reference to a non proxy model. I have read the discussion pointed here and tried some of the approaches shown, however None of them has worked for me. So right now I'm trying to update the generated model to point to the proxy one, which I think should not cause any problem. As I have seen that Django generated a migration for the unmanaged models, I thought that makemigration would detect the change in the FK for that model. However, when I run manage.py makemigrations It shows that no changes were detected. Is … -
API for rendering regular Django template VS API for
I am writing a web site using Django REST framework. This is my first days with the REST, so please bear with me. Basically, the question is, Can I come up with a class-based view which could serve both as an API for Android developers (with JSON response) and a view rendering regular Django template? Or I have to define two different views for this purpose ? If the answer to question 1 is that I have to define two separate views, then what is the most DRY method to that taking into account that the querysets are the same ? class TestList(APIView): renderer_classes = [TemplateHTMLRenderer] template_name = 'android/test.html' def get(self, request): queryset = Test.objects.all() return Response({'test_qs': queryset}) # WHAT ABOUT JSON RESPONSE ??? -
Type object has not attribute 'get_or_create'
For reasons unknown only one (out of 18) of my Django models is throwing the error "type object 'LidarReading' has not attribute 'get_or_create'". Model declaration is below. class LidarReading(models.Model): value = models.DecimalField(max_digits=10, decimal_places=2) roll = models.DecimalField(max_digits=12, decimal_places=4) pitch = models.DecimalField(max_digits=12, decimal_places=4) yaw = models.DecimalField(max_digits=12, decimal_places=4) coordinates = models.ForeignKey('FlightCoordinate', models.SET_NULL, blank=True, null=True) created = models.DateTimeField(auto_now_add=True, blank=True, null=True) modified = models.DateTimeField(auto_now=True) Call in Django command is as follows (note that 'flight_coordinate' is a FlightCoordinate model object created using get_or_create above): lidar, created = LidarReading.get_or_create(value=t['lidarreading_value'], roll=t['lidarreading_roll'], pitch=t['lidarreading_pitch'], yaw=t['lidarreading_yaw'], coordinates=flight_coordinate, created=t['lidarreading_created']) Thanks in advance for the assistance. -
Does Django checks if a QuerySet has already been evaluted?
I couldn't find a way to print out when Django is actually hitting the database from a QuerySet method, but according to the docs, my example below should unnecessarily perform two queries, or does it? queryset = MyModel.objects.all() #Slicing evaluates a query queryset = queryset[5:10] #Serializing should also evaluate a query data = serializers.serialize('json', queryset, fields=('pk', 'name')) -
SlickJS Carousel HTML5 video play/pause button
I have a SlickJS carousel that is part of a Django template. The Django database provides the data for the carousel slides. If I use controls on the videos they play/pause fine. I want to use a button to toggle play/pause for each slide (instead of controls) and pause the video when the slide changes. The button doesn't play/pause the video (I think it isn't picking up the video element correctly). This is close to what I want,but it works with Youtube instead of HTML5 video and the source of the video is static whereas mine is dynamic from a database that changes over time. HTML for video: <video class="hero" id="bgvideo" preload="none" poster="{% static 'films/'|add:film.imdb_id|add:'/'|add:film.backdrop %}"> <source src="{% static 'films/'|add:film.imdb_id|add:'/'|add:film.trailer1|add:'.mp4' %}" type="video/mp4"> <source src="{% static 'films/'|add:film.imdb_id|add:'/'|add:film.trailer1|add:'.webm' %}" type="video/webM"> <source src="{% static 'films/'|add:film.imdb_id|add:'/'|add:film.trailer1|add:'.ogv' %}" type="video/ogg"> <p>Your browser does not support the video tag.</p> </video> <button class="btnPlay" type="button">Play/Pause</button> JS for SlickJS carousel <script type="text/javascript"> $(document).ready(function(){ $('.hero-slider').slick({ slidesToShow: 1, slidesToScroll: 1, arrows: false, fade: true, asNavFor: '.slider-nav' }); $('.slider-nav').slick({ slidesToShow: 6, slidesToScroll: 1, asNavFor: '.hero-slider', dots: false, arrows: true, centerMode: true, autoplay: true, autoplaySpeed: 10000, focusOnSelect: true }); </script> JS to play/pause video <script> var video = document.getElementById("bgvideo"); $('.btnPlay').on('click', function() { if(video[0].paused) { … -
Django - filtering ManyToMany through by category
So I have a set of models that use a manytomany through relationship, and I need to filter my an attribute of the related model class Service(models.Model): name = models.CharField(max_length=100, null=False) category = models.CharField(max_length=100, null=False, choices=( ('primary', 'Primary'), ('referral', 'Referral'), ('mental', 'Mental/Behavioral'), ('spiritual', 'Spiritual'), ('social', 'Social'), )) class Facility(models.Model): service_unit = models.ForeignKey(ServiceUnit, null=True, blank=True) services = models.ManyToManyField(Service, through='FacilityService') name = models.CharField(max_length=100, null=False) phone = models.CharField(max_length=25, null=True, blank=True) class FacilityService(models.Model): service = models.ForeignKey(Service, null=False) facility = models.ForeignKey(Facility, null=False) name = models.CharField(max_length=100, null=True, blank=True) What I need to do is in my view return a list of the facilities that that have services in a specified category. Each facility can have multiple services, and each service has a category assigned to it. Here is my view so far: def get_facility_services(request): spec = int(request.GET.get('service')) facilityList = [] for facility in Facility.objects.all: found = 0 for service in facility.services.all: cat = service.category if (spec == cat): found = 1 if (found == 1): facilityList.append(facility.pk) facilities = Facility.objects.filter(pk__in=facilityList) to_return = serialize('json', facilities) return HttpResponse(to_return, content_type='application\json') I have tried several different methods of filtering to try and accomplish this, but nothing has been fruitful so far. Any help would be greatly appreciated! -
Setting custom HTML template for Django REST framework mix-ins
I am just starting to explore Django REST framework. So please bear with me :) I have a working code with generic class-based views deploying REST frameworks' mix-ins: View: class TestList(generics.ListCreateAPIView): queryset = Test.objects.all() serializer_class = TestSerializer class TestDetail(generics.RetrieveUpdateDestroyAPIView): queryset = Test.objects.all() serializer_class = TestSerializer Respective part of URL conf: url(r'^test/$', test_views.TestList.as_view(), name = 'test'), url(r'^test/(?P<pk>[0-9]+)$', test_views.TestDetail.as_view(), name= 'test'), The question is, how can I keep this concise code powered by mix-ins, and at the same time pass on a custom HTML template ? -
Keep data in a variable after deletion of an object in Django
I am on Django 1.9 I would like to keep a list of ids after I deleted the objects having these ids (to be sent back to an Ajax function). But because I delete these objects, the list is also emptied. Here is my code: relatedsteps = Step.objects.filter(theplace=theplaceclicked) listofrelatedstepsid = relatedsteps.values('id') response_data = {} response_data['listofrelatedstepsid'] = listofrelatedstepsid print(response_data['listofrelatedstepsid']) relatedsteps.delete() print(response_data['listofrelatedstepsid']) The first print(response_data['listofrelatedstepsid']) returns [{u'id': 589}] But the second one returns: [] Any clue? Thanks a lot -
Django cut queries to get only "nth to nth" results
I'm coding a multi page table view using in Javascript using AJAX/Jquery, the database has a lot of records so every time user changes page a new query will be asked from the served and only those showed will be sent So let's say user clicks page 5 and has chose to display 15 results per page, the view should query the results but only send from the (5*15)nth to the (6*15)nth objects. 1) How exactly can you cut a QuerySet as described above? 2) Is there a way to include this in the Query itself for better performance? Or do I need to first call MyModel.objects.all() and then cut the results? -
Sharing cookies across domains and subdomains
I'm trying to implement a multi-tenancy architecture with Django and django-tenant-schemas. I'm successfully accessing the baseapp from http://app.mysite.com:8000/ and setting a cookie sessionId (which is http-only) when I log into the application. (Port 8000 is only for development) I'm now trying to make a request to http://tenant1.mysite.com:8000/accounting/. When I inspect the request headers, however, I see that the cookies have not been set even though in my settings file I have: SESSION_COOKIE_DOMAIN = ".mysite.com" CSRF_COOKIE_DOMAIN = ".mysite.com" I was under the impression that setting my cookie domain to .mysite.com would allow access to subdomains. What am I missing here? -
Django one to many model ORM access
I have two models, Person and Classes, both these models do not have any database tables corresponding to it (meta managed=false), but are populated by a custom query. Is it possible to get the related fields using the ORM. Example: can I do person.classes and get the related records? -
how get new message in telegram bot using django
bot = telepot.Bot('264905644:AAEfkdFDZGNOFQD3ahimynC414fcaY') data = request.body response = json.loads(data) chat_id = response['message']['chat']['id'] message = response['message']['text'] I have set webhook and i dont know how to get new messages? -
Django - Custom Auth Class, Token OR Session
I need to write a class that will provide SessionAuthentication and TokenAuthentication on DJango 3.0 That means - if user have a valid session OR a valid token he is authenticated. I have both classes but I have no idea how to combine them: TOKEN: def authenticate(self, request): auth = get_authorization_header(request).split() if not auth or auth[0].lower() != self.keyword.lower().encode(): return None if len(auth) == 1: msg = _('Invalid token header. No credentials provided.') raise exceptions.AuthenticationFailed(msg) elif len(auth) > 2: msg = _('Invalid token header. Token string should not contain spaces.') raise exceptions.AuthenticationFailed(msg) SESSION: def authenticate(self, request): """ Returns a `User` if the request session currently has a logged in user. Otherwise returns `None`. """ # Get the session-based user from the underlying HttpRequest object user = getattr(request._request, 'user', None) # Unauthenticated, CSRF validation not required if not user or not user.is_active: return None I also tried on settings.py: REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.TokenAuthentication', ) } but it did not work our, I think this is checking token AND session.. Any ideas? -
Django ordering in admin
I have the following model: class Article(models.Model): fabric = models.CharField(max_length = 10) color = models.CharField(max_length = 10) supplier = models.CharField(max_length = 50) def __str__(self): return str(self.id) class Import(models.Model): packing_list = models.ForeignKey(PackingList) article = models.ForeignKey(Article) quantity = models.IntegerField() comment = models.CharField(max_length = 200) def __str__(self): return str(self.id) In admin.py I have the following code: class ImportAdmin(admin.ModelAdmin): def fabric(self,obj): return obj.article.fabric def color(self,obj): return obj.article.color def supplier(self,obj): return obj.article.supplier list_display = ['id', 'fabric', 'color', 'supplier','quantity','comment'] search_fields = ['packing_list__name'] and in my admin panel I would like to sort the fields by fabric. I tried doing ordering = ('fabric', ) but I am unable to do that because fabric is not an attribute of Import. Is there any way to do this? -
jQuery datetimepicker- unable to select date from next year
I am working on a Python/ Django project, and one of the forms on a webpage has a datetimepicker field on which the user can select a date/ time from the drop-down that appears when the field is selected. The problem that I currently have is that although the calendar displays a full month at a time, and the user can move through months/ years at a time by selecting next/ previous month, or choosing the year from a drop down inside the calendar, if they move to a month beyond the end of this year, then none of the dates are available for selection. Having Google'd datetimepicker, it seems that this is a jQuery function, and I want to make sure that there is no value for its maxDate attribute- I've looked through jquery.datetimepicker.full.js, and although it's referenced there, it doesn't see to be given a value at all... so I can't see why this field is not allowing me to select a date beyond the end of this year... anyone have any ideas? The view that is rendering this page is: def concept(request, project_id): project = Project.objects.prefetch_related('budget_versions').get(id=project_id) deposit = Deposit.objects.get_or_create(project=project)[0] presentations = project.budget_versions.select_related('meeting').prefetch_related('budget_items', 'cci_items', 'presenters').filter(version_number__isnull=False).annotate(vn=F('version_number') * -1).order_by('presentation_date', 'created', … -
Get only certain fields of related object in Django
Say I have such models in Django: class User(models.Model): name=models.CharField(...) email=models.EmailField(...) photo=... <other fields> class Comment(models.Model): user=models.ForeignKey(User, ...) I have a function that receives Comment object and needs just name and email fields to send email (it is just example, obvious) def sendEmail(comment): name, email=comment.user.name, comment.user.email In implementation presented above, Django will fetch all fields of related object User (something roughly equal to select * from users where id=comment.user_id) Using values_list I can fetch just needed fields: Users.objects.filter(id=comment.user_id).values_list('name', 'email') but values_list only applicable to QuerySet object, not to model instance. My question is: is there any way to do the same thing using only "comment" object? I know also there are -
Serving djangocms project from subfolder
My site is currently running with: nginx, uwsgi, django (with djangocms). I need to move everything under a subfolder /abc nginx location /abc { uwsgi_pass rak; include /etc/nginx/uwsgi_params; uwsgi_modifier1 30; uwsgi_param SCRIPT_NAME /abc; } The site works well but when I try to load any cms page I get 404 or the "Create page" wizard. All the other apps are correctly served under the /abc/ subfolder even when attached to the cms via apphook. The url reverse works good and the admin site is ok. Am I missing something? -
ElasticBeanstalk Docker w/ Supervisor vs ElasticBeanstalk Multicontainer Docker
We are working on a new REST API that will be deployed on AWS ElasticBeanstalk using Docker. It uses Python Celery for scheduled jobs which means separate process need to run for workers, our current Docker configuration has three containers... Multicontainer Docker 09c3182122f7 sso "gunicorn --reload --" 18 hours ago Up 26 seconds sso-api f627c5391ee8 sso "celery -A sso worker" 18 hours ago Up 27 seconds sso-worker f627c5391ee8 sso "celery beat -A sso -" 18 hours ago Up 27 seconds sso-beat Conventional wisdom would suggest we should use a Multi-container configuration on ElasticBeanstalk but since all containers use the same code, using a single container configuration with Supervisord to manage processes might be more efficient and simpler from an OPS point of view. Single Container w/ Supervisord [program:api] command=gunicorn --reload --bind 0.0.0.0:80 --pythonpath '/var/sso' sso.wsgi:application directory=/var/sso [program:worker] command=celery -A sso worker -l info directory=/var/sso numprocs=2 [program:beat] command=celery beat -A sso -S djcelery.schedulers.DatabaseScheduler directory=/var/sso When setting up a multi-container configuration on AWS memory is allocated to each container, my thinking is it more efficient to let the container OS handle memory allocation internally rather than to explicitly set it to each container. I do not know enough about how Multi-container Docker … -
Django slice a single field in a queryset
I am trying to grab the first five characters from a char field but for only one field in a queryset but I keep getting various errors. Is there an effective way to do this in the view? Code I am trying: var = Model.objects.values('field1', 'field2'[:5], 'field3') -
memory usage never go down unless inactivity-timeout not set
Part of /etc/apache2/sites-enabled/myproject.conf: WSGIDaemonProcess myporject user=tester group=tester processes=2 threads=5 python-eggs=xxx display-name=xxx When one user started browsing the website, memory used was increased by 80M (from output of free -m) and the memory usage would not go down even though the user logged out and shut down the browser, unless running service apache2 restart. I tried worker mode and prefork mode, but still not released. When inactivity-timeout set to 60 seconds, memory usage will go down 60 seconds after log out. I am new to apache2 and wsgi configuration. I just wonder whether setting inactivity-timeout is the good way for the memory usage to go down? Any other important configuration missing? Any comments welcomed. If more information needed, please tell me. Thanks -
django-rest-swagger: How can I specify the parameter for POST requests while using APIView
In the latest version on dajngo rest swagger(2.1.0) YAML docstrings have been deprecated. I cannot get swagger to show the POST request parameters. Here is my view class UserAuthenticationView(APIView): def post(self, request, *args, **kwargs): serializer = UserAuthenticationSerializer(data=self.request.data) if serializer.is_valid(): user = serializer.validated_data['user'] return Response({'token': user.auth_token.key}, status=status.HTTP_200_OK) return Response(serializer.errors, status=status.HTTP_401_UNAUTHORIZED) Here is my Serializer class UserAuthenticationSerializer(serializers.Serializer): username = serializers.CharField() password = serializers.CharField() def validate(self, attrs): username = attrs.get('username') password = attrs.get('password') if username and password: user = authenticate(username=username, password=password) if user: if not user.is_active: msg = 'User account is disabled.' raise serializers.ValidationError(msg, code='authorization') else: msg = 'Unable to log in with provided credentials.' raise serializers.ValidationError(msg, code='authorization') else: msg = 'Must include "username" and "password".' raise serializers.ValidationError(msg, code='authorization') attrs['user'] = user return attrs This is what I get in my generated I do not get a form with the fields for the POST data. How do I get that? -
Need to save after QuerySet update?
I need to updates all the entries in my database that meet a certain condition. I can obtain them by filtering the correspondent model and update them using the update method on the obtained QuerySet, but I don't know if I have to execute the save method on every object of the QuerySet to save the changes or if the changes are saved to the DB automatically. -
Python/ Django- datetimepicker won't allow user to select date from next year
I have a site that has been written in Python/ Django, and have a number of forms on the various pages. Some of the forms have a 'date' field, which is of type datepicker. When selected, these fields display a 'calendar' drop down, that show a single month at a time, and allow the user to click on a date from that month- when the user selects a date, the field is populated with that value. The user can select a date from the current month (which is the month automatically displayed when the user clicks the field), or select the <, >, arrows or month or year drop downs to choose to display another month, and select a date from that. However, on one of the forms, there's a datetimepicker field- when the user clicks the field, a 'drop down' appears, displaying a 'calendar' view of the current month, and allowing the user to select a date from the month, by clicking one of them. But for some reason, all of the values beyond the end of the current month (December 2016) are 'greyed out', and it is not possible to select them... As far as I can tell, …