Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django : pagination for two different models
I am working on a Django (v1.11.0) project and I have two models called Song that contain users songs and GenericSong that contain administration songs. class Song(models.Model): album = models.ForeignKey(Album, on_delete=models.CASCADE) song_title = models.CharField(max_length=250) audio_file = models.FileField() is_favorite = models.BooleanField(default=False) def __str__(self): return self.song_title class GenericSong(models.Model): album = models.ForeignKey(GenericAlbum, on_delete=models.CASCADE) song_title = models.CharField(max_length=250) audio_file = models.FileField(default='') is_favorite = models.BooleanField(default=False) def __str__(self): return self.song_title I want to list all the songs in the database which contain users and administration songs, the problem is, I want to list that with a pagination. I did this for a page that contain only users songs using this view, which is working just fine : @login_required() def songs(request, filter_by=None): users_songs = Song.objects.filter(album__user=request.user) page = request.GET.get('page', 1) if filter_by == 'favorites': users_songs = users_songs.filter(is_favorite=True) paginator = Paginator(users_songs, 10) try: songs_page = paginator.page(page) except PageNotAnInteger: songs_page = paginator.page(1) except EmptyPage: songs_page = paginator.page(paginator.num_pages) return render(request, 'music/songs.html', { 'song_list': songs_page, 'filter_by': filter_by, }) But in the second view, I don't know how to make song and genericsong in one variable to make tha pagination, here is the all songs view that I want to make changes to it : @login_required() def all_songs(request, filter_by=None): users_songs = Song.objects.all() generic_songs = … -
Django accese related model
theres's something I'm missing or don't understand, maybe a very basic concept. I have two models Person and Student, related by a OneToOneField like this: class Student(models.Model): person = models.OneToOneField( Person, on_delete = models.CASCADE, ) # fields definition Should't I be able to access Student from Person with student_set? Like this, but I get de error as follows: >>> from people.models import Person >>> p = Person.objects.get(pk=6) >>> p.student_set.all() Traceback (most recent call last): File "<console>", line 1, in <module> AttributeError: 'Person' object has no attribute 'student_set' >>> Thanks! -
Daemon process alongside django
Like to see what others think the best architecture for the following. I am trying to build a project that with a web front end that has the requirement to issue commands to other long running processes that will return results to the django db. The app must be scalable (in both db and processing power) and be able to run quickly. I've thought of the following scenario but wanted to check if there is a better way. Django web app receives instructions from a user (via web form or API) puts this 'request' into a queue (which technology would be best?) that another process (running asynchronously to gain performance, no startup costs) can consume (how does it do this? By monitoring a queue? IPC?). This app then returns the result of it's processing which needs to be put back into the django db (best to do this by another queue or direct access?) Thoughts on sanity...and technology. Links to tutorials would be great! How to run the asynchronous process. Celery, host daemon process? How to get data to and from the main django app/db. Queues, socket IPC? Use of django signals in here somewhere?! -
Why my django program is not working?
I am a beginner of Django . I started learning django very early . But now my program is not running ? what is wrong with it? -
share login across domain without cas server
How would I share django login authentication across domains? The app is hosted on heroku and the other domains simply point to the app and the urls are rerouted according to the domain. I tried setting cookies per domain but this didn't work. CAS server isn't an option. What are other options? -
requests.post hanging for a minute locally
I am attempting to post to recaptcha via Python requests module. I have had no problems until recently there is a one minute delay for the post request to process, only locally. In Heroku production there is no delay. Possible reasons why this issue might have just now cropped up locally? I have 127.0.0.1 as a valid domain for the recaptcha. accesscode = request.POST.get('g-recaptcha-response') url = 'https://www.google.com/recaptcha/api/siteverify' secret = settings.RECAPTCHA_PRIVATE_KEY postdata = { 'response': accesscode, 'secret': secret, } r = requests.post(url, data=postdata) -
Django Rest Framework Validate Child in ListField
I have created a list of DictField instances. Here is my serializer.py class DetailSerializer(serializers.Serializer): """Serialize order""" id = serializers.IntegerField(read_only=True) order= serializers.IntegerField(min_value=1) class OrderSerializer(serializers.ModelSerializer): orderlist = DetailSerializer(many=True) Now I want to do validation for orderlist like make sure every order in this list is strictly_increasing and unique. How can I do? -
How do i bind a react component to the database state?
I want to bind the state of a react component to a backend server running on Django. What i am trying to achieve is an ajax call that constantly updates the state of the component, however, constantly making an api call after every couple of seconds might have an impact on the performance of the application and hence, i am looking for a better way to achieve the same. -
How can I authenticate user both in websockets and REST using Django and Angular 4?
I would like to authenticate user both in websockets and REST using Django and Angular 4. I have created registration based on REST API. User after creating an account and log in can send messages to backend using websockets. My question is how can I know that the user authenticated by REST API (I use Tokens) is the same user who sends messages? I don't think that sending Token in every websocket message would be a good solution. Do you have any ideas? -
I need a blog app for my Django project
I'm going to add a "/blog/" to my django project and somehow I do not want to write it from scratch. So i'm looking for a blog app (like WordPress) and even have found some but they are either so simple or they're not an APP (like Mezzanine). So what do you suggest? -
How to create foreign key related objects during object create call with the Django Rest Framework?
Let's say I have model A and B. Model A has a range of fields including a user field which is filled in with the user who creates an object A. When object A is created I want to create a bunch of object B's using the user that created object A and possible using object A itself as a foreign key. My Model A ViewSet looks like this: class OrganizationViewSet(DynamicModelViewSet): queryset = Organization.objects.all() serializer_class = OrganizationSerializer permission_classes = (IsAdminOfPermission,) So when an organization is created I want to create a bunch of object B's using the user that created the organization and possibly using the organization object itself. How do I do this? -
How to extract a list of points from Django PolygonField?
In one of my models that contains a PolygonField I have a to_dict method that takes all the values and turns them into a readable dictionary. I do a similar thing for a model that has a PointField and it looks like this: 'point': { 'type': 'Point', 'coordinates': [self.point.x, self.point.y] }, For the PolygonField I have to loop through the points to put them in the dictionary. I tried this but as expected, django complained: 'polygon': { 'type': 'Polygon', 'coordinates': [ for point in self.path: [point.x, point.y] ] }, How do you add all the points from a PolygonField into a dictionary? -
Django updating dropdown list from selection
I'm using class-based views to populate a form. My model has two many-to-one foreign keys. I want to populate one of the dropdowns depending on the other dropdown which is based on the foreign keys. models.py class Assignment(models.Model): is_section = models.BooleanField(default=False) assignment_self = models.ForeignKey('self', null=True, blank=True, limit_choices_to={'is_section': True}, verbose_name='Assignment', on_delete=models.CASCADE) assignment_course = models.ForeignKey('Course', default=None, null=True, blank=True, on_delete=models.CASCADE) In views.py, the 'assignment_self' is the queryset I want to update when the dropdown for assignment_course is updated. class AssignmentCreate(CourseMixin, CreateView): model = Assignment fields = ['is_section', 'assignment_self', 'assignment_course'] def get_initial(self): pk = self.kwargs['pk'] course = Course.objects.get(pk=pk) return {'assignment_course': course} def get_form(self, form_class=None): pk = self.kwargs['pk'] course = Course.objects.get(pk=pk) form = super(AssignmentCreate, self).get_form(form_class) form.fields['assignment_self'].queryset = Assignment.objects.filter(assignment_course=course) return form assignment_form.js $('#id_assignment_course').change(function(){ $('#section-modal-label').text("Add to " + $('#id_assignment_course option:selected').text()); $.ajax({ type: 'GET', data: { course_selected: $('#id_assignment_course option:selected').text(), }, success: function(result){ alert('ok'); }, error: function(result){ alert('error'); } }) }) assignment_form.hml {{ form.as_p }} urls.py url(r'^add_assignment/(?P<is_section>\d+)/(?P<pk>\d+)/$', AssignmentCreate.as_view(), name='add_assignment'), How do I get the course_selected from the assignment_form.js to the views.py? -
Log http requests in db table with django and tastypie without increase response time
I have android app on which my django server is sending some push notifications using firebase cloud messaging. As soon as client received the notifications, it makes a GET request to my API written using Tastypie. I want to somehow store this GET request in my Log table so that I can ensure that my android app is working fine and make right requests on receiving notifications from server. On one of the answers, I read that it can be achieved by overriding the dispatch function for Model Resource in tastypie. Could this logging be achieved without overriding the dispatch because it can potentially increase the response time. -
Querying / Retrieving Data from SQL Server using Django
I am pretty new to Django. I am trying to query data from SQL server using a Django App. I am able to connect with the default Django database and fetch data from there but Django keeps throwing an error when I try to query an existing database. (Apologies for indentation mistakes in formatting here but it is ok in my scripts) views.py shows the following error: from django.http import HttpResponse from django.template import Context,Template,RequestContext from django.shortcuts import render_to_response, render from django.conf.urls.static import static from django.contrib import admin from django.contrib.staticfiles.urls import staticfiles_urlpatterns from django.template.context_processors import csrf from ForecastApp.forms import * from django.core.mail import send_mail from django.utils.safestring import mark_safe #from django.db import connection import os import csv import json import subprocess from subprocess import * from operator import itemgetter from datetime import datetime import pyodbc from logging import getLogger from .models import Actuals from .models import forecastfuture ss = forecastfuture.objects.using('default').all() print len(ss) for row in ss: print (row.region) #works fine tt = Actuals.objects.using('Forecasting').all() print len(tt) for row in tt: print (row.Region) [Microsoft][SQL Server Native Client 11.0][SQL Server]Invalid column name 'id'. (207) I have set up routers.py and models.py and settings.py per instructions in documentation. routers.py class App1Router(object): #pardon my poor indentations … -
Django-shared-session is not working properly despite instructions
Does anyone have an example of using django-shared-session successfully? Per the instructions I've set the domains included the shared session tempalte tags etcetera. However, the login between domains isn't being shared despite the package saying it will share logins and session data. -
Django + PostgreSQL trigger causes "violates foreign key constraint"
In my Django... schema? I have a model structure for Products, their prices and a historic (kind of a log) of the prices the products went through. A bit like the following (simplified for this question): class ProductPricing(models.Model): price = models.DecimalField(max_digits=8, decimal_places=2, help_text='price in dollars') product = models.OneToOneField('app.Product', related_name='pricing', null=False, on_delete=models.CASCADE) class Product(models.Model): name = models.CharField(max_length=100) # .pricing --> related name from 'ProductPricing' To keep the history of the prices, I have an OldProductPricing model, which is pretty much a copy of ProductPricing but allows multiple OldProductPricing(s) per product: class OldProductPricing(models.Model): valid_until = models.DateTimeField(null=False) product = models.ForeignKey('app.Product', related_name='+', null=False, on_delete=models.CASCADE) To make sure that each and every time that a product's price is modified or deleted, I try to create an entry in my OldProductPricing table. In order to do that, I have created a Posgresql trigger on update or delete: CREATE TRIGGER price_change_trigger AFTER UPDATE OR DELETE ON app.productpricing FOR EACH ROW EXECUTE PROCEDURE price_change_trigger_func(); The part of the trigger function that creates the insertion is as follows: CREATE OR REPLACE FUNCTION price_change_trigger_func() RETURNS TRIGGER LANGUAGE plpgsql AS $$ DECLARE retval RECORD; BEGIN IF (TG_OP = 'DELETE') THEN retval := OLD; ELSE retval := NEW; END IF; RAISE LOG … -
How to start download immediately (but can't chunk data)?
I have a view like this: def download(request): response = StreamingHttpResponse([save_virtual_workbook(make_xl_workbook())], content_type="application/vnd.ms-excel") response[u'Content-Disposition'] = u'attachment; filename="%s"' % filename return response But it waits to prompt the user to download until after make_xl_workbook has run. I was reading that I can't chunk out the data returned from make_xl_workbook because xlsx files are zipped. So I was hoping to start the download right away, then run the function and then pump the full data into the response once that function has run. I also tried this but it didn't seem to help: def download(request): def save_xl(): yield save_virtual_workbook(make_xl_workbook()) response = StreamingHttpResponse(save_xl(), content_type="application/vnd.ms-excel") response[u'Content-Disposition'] = u'attachment; filename="%s"' % filename return response -
Django - iterating through generic detailview context in html
Can someone help me understand when passing context to the HTML template using the detailview class why a for loop can't be used to iterate through the contents in the html page? I'm able to access the context variable directly by name to display the values: collection_details.Name or collection_details.date but when using a for loop to iterate, it doesn't work. views.py: class AcqSummaryView(DetailView): model = AcqSummary context_object_name = 'collection_details' def get_context_data(self, **kwargs): context = super(AcqSummaryView, self).get_context_data(**kwargs) return context html: {% for item in collection_details.items %} <p>{{ item }}</p> {% endfor %} -
How to delete Django object after countdown?
In the platform I am working on we want users to be able to set expiry times on the objects they create. After the countdown they set expires, that object should be deleted. How would you recommend doing this? -
Filtering Birthdays at specific date range inside date fields
I'm struggling to filter birthdays at born dates using django rest framework and django-filters (http://django-filter.readthedocs.io/en/master/). The biggest problem is that using django common filters I would need to do something like class birthdayFilter(django_filters.rest_framework.FilterSet): day = django_filters.RangeFilter(name="born_date__day") month = django_filters.RangeFilter(name="born_date__month") class Meta: Model = User fields = ['day','month'] The problem occurs if the user selects a time period like this: 27/11 to 1/12 In this case I would always receive an empty server response, because by default it would try to get dates with days bigger than 27 and lower than 1, which is always none. Another problem is if the user selects something like: 27/10 to 1/01 or 27/10 to 1/12 I think the solution is to get my hands dirty and write my own filter, but the documentation of django filters is not clear about how to do that. -
simple way to add existing users database(non django) to django
O.K. I have a headache with this problem. I have to different sites(non django) with login option and I would like to join in it into one new website based on django. Each of these two user databases consist of table with columns:(username, password, e-mail). The problem is, I just can not copy it to User table in Django as we all know django is very rigid about it, so I am trying to think a way, existing users would be able to login to site as nothing has changed. Is there any django/pythonic way to do so? I was thinking to create an app, which would take a foreign key to User model. Within User model I would create two users (database_1, database_2), so whenever a user from database 1 would login, e.g. JohnSmith, he would be connected as database_1 user, but so would JessicaSimpson if she would be in database 1. I am just thing to create Authentication and Authorization app as system app in some way... Is this a right way thinking? Would love to hear from professionals. Thanks -
Django inheritance - accessing child class fields
I have the following Django models: class Image(TimeStamp): hash = models.CharField(max_length=33, unique=True, editable=False) filesize = models.PositiveIntegerField(blank=True, null=True, editable=False) class Image1(Image): image = models.ImageField(upload_to='image1/') class Image2(Image): image = models.ImageField(upload_to='image2/') I want to be able to automatically compute filesize and hash upon image creation and the most reasonable place seems to me in a super class. However, I need to be able to access child class image field from the super class in order to compute hash and filesize. Is there a way to achieve this? I added this save method to the superclass, but of course it doesn't know about image: def save(self, *args, **kwargs): super(Image, self).save(*args, **kwargs) self.hash = hashlib.md5(self.image.read()).hexdigest() self.filesize = self.image.size -
¿Custom pk in PUT method of Django ModelViewSet?
I´m trying to provide a url 'perfil/update' to the user for update hiself data in a Model called 'Perfil'. class Perfil(viewsets.ModelViewSet): serializer_class = perfilSerializer permission_classes = (IsAuthenticated) def get_queryset(self): queryset = PerfilModel.objects.all().filter(username=self.request.user) return queryset def put(self, request, pk, format=None): request.data['iduser'] = 6 serializer = perfilSerializer(user, data=request.data, partial=True) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) How I would can set request.data['iduser'] = 6, for every update my iduser save as '6' only accessing to 'perfil/update'? Thanks! -
Add my own query parameters to django admin
I have a model that uses latitude and longitude fields for location. One of the queries that I want to run using query params is search around a specific radius. I have the queryset read and I override it: queryset = super().get_queryset(request) if 'radius' in request.GET: queryset = queryset.in_distance(request.GET['radius'], fields=['location__latitude',location__longitude'], points=[lat, lon]) return queryset When calling my admin page with /admin/dal/listing?radius=50 I get redirected to the admin without the query string. Followed Django's code and found this: # At this point, all the parameters used by the various ListFilters # have been removed from lookup_params, which now only contains other # parameters passed via the query string. We now loop through the # remaining parameters both to ensure that all the parameters are valid # fields and to determine if at least one of them needs distinct(). If # the lookup parameters aren't real fields, then bail out. try: for key, value in lookup_params.items(): lookup_params[key] = prepare_lookup_value(key, value) use_distinct = use_distinct or lookup_needs_distinct(self.lookup_opts, key) return filter_specs, bool(filter_specs), lookup_params, use_distinct except FieldDoesNotExist as e: six.reraise(IncorrectLookupParameters, IncorrectLookupParameters(e), sys.exc_info()[2]) In a nutshell because the query string is not a known field django gracefully panics and redirect a not filter admin page. What can …