Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django ValueError at /feed/new/
I am trying to create the feed part of my social mini social network project. I have a "feed" app which handles all the user posts. Everything works except when I go to submit the post on the user post_form page I get this error: ValueError at /feed/new/ invalid literal for int() with base 10: 'User' I'm not really sure what the issue is, but here is my code. Also the traceback doesn't highlight anything, but if you want to see it let me know. Feed app urls: from django.conf.urls import url from feed import views app_name = 'feed' urlpatterns = [ url(r'^new/$',views.CreatePostView.as_view(),name='new_post'), url(r'^post/(?P<pk>\d+)/edit/$',views.UpdatePostView.as_view(),name='edit_post'), url(r'^post/(?P<pk>\d+)/delete/$',views.DeletePostView.as_view(),name='delete_post'), url(r'^post/(?P<pk>\d+)/comment/$',views.add_comment_to_post,name='add_comment_to_post'), ] Feed app Views: from django.shortcuts import render,get_object_or_404,redirect from django.utils import timezone from feed.models import UserPost,UserComment from feed.forms import PostForm,CommentForm from django.urls import reverse_lazy from django.contrib.auth.decorators import login_required from django.contrib.auth.mixins import LoginRequiredMixin from django.views.generic import (TemplateView,ListView, DetailView,CreateView, UpdateView,DeleteView) # Create your views here. ##Posts Views class HomeView(LoginRequiredMixin,ListView): login_url = 'login' model = UserPost ordering = ['-post_date'] class CreatePostView(LoginRequiredMixin,CreateView): login_url = 'login' redirect_field_name = '/userpost_list.html' form_class = PostForm model = UserPost class UpdatePostView(LoginRequiredMixin,UpdateView): login_url = 'login' redirect_field_name = '/userpost_detail.html' form_class = PostForm model = UserPost class DeletePostView(LoginRequiredMixin,DeleteView): model = UserPost success_url = reverse_lazy('userpost_list') ##Comments Views … -
Django REST Framework Routing
Hello having problems figuring out what the best approach would be to create a set of routes like these below. Routes are pseudocode and subject to change. Currently using Django 1.11 GET /api/<model>/<id> GET /api/<model>/?select=<feld1>,<feld2>,<feld3>,... GET /api/<model>/?top=20&skip=60 GET /api/<model>/<id>/<model2> # Where Model2 is also a parameter which can change GET /api/<model>/?expand=<model2>,<model3>,... GET /api/<model>/?filter=<filter-string> GET /api/<model>/?search=<solr-query> -
Best way to efficiently store (and be able to filter by) hashes in Django
I'm trying to create a Django app where I can look up the hash of a file (md5, sha1, or sha256) in order to get back attributes of that file. Currently, I'm struggling with making a decision on how to efficiently store those values in the database. I've seen Django's BinaryField, but unfortunately, that appears geared towards purely storage of a password (hash), and the documentation explicitly mentions that you cannot filter on that field when dealing with a QuerySet. This however, is of critical importance for my application. I've seen another post on SA regarding storing MD5 hashes specifically, where it is called out (with good performance numbers) that Django's UUIDField is a perfect fit. However, a UUIDField doesn't support more than 16 bytes, and so doesn't work for SHA1 or SHA256 hashes. I've looked online to see if someone has come up with a Custom Field implementation for this but came up dry. Does anyone have a good idea on how to proceed? I'm specifically trying to avoid storing the hash as (say) base64 or the hexstring equivalent (using a CharField); I want to just store the bytes of the hash. It seems strange to me that I … -
Switching django-cms project from sqlite to postgres
I'm trying to switch database backends for an existing django-cms project, from sqlite3 to postgresql. When I start with a fresh sqlite database and apply all migrations everything works fine. If I do the same with a fresh postgres database everything appears to go ok but I get the following error when trying to do anything: django.db.utils.ProgrammingError: relation "cms_urlconfrevision" does not exist LINE 1: ...sion"."id", "cms_urlconfrevision"."revision" FROM "cms_urlco... I get a warning while running runserver that there are unapplied migrations despite the fact that a listing of migrations shows all applied, and running migrate again does nothing (makemigrations also does nothing). The cms_urlconfrevision table exists in the database, with the Id and revision fields, so I'm at a loss for where to look further. -
Correct way of handling deletion of django-mptt nodes
I have a Django model Product and ProductCategory (using django-mptt) that look like this: class ProductCategory(mptt.models.MPTTModel): name = models.CharField(max_length=256) parent = mptt.models.TreeForeignKey('self', null=True, blank=True, related_name='children', db_index=True, on_delete=models.DO_NOTHING) class Product(models.Model): name = models.CharField(max_length=256) category = models.ForeignKey(ProductCategory, on_delete=models.DO_NOTHING, null=True, default=None) I want to create logic that on deletion of the product_category node all the linked products will get linked to the parent of deleted node. I achieved it with the following code: @receiver(pre_delete, sender=ProductCategory) def pre_delete_product_category(sender, instance, using, **kwargs): products = instance.products.all() categories = instance.children.all() for p in products: p.category = instance.parent p.save() for c in categories: c.parent = instance.parent c.save() This is working but I have impression there should be a better way. In particular I would like to disallow null links to category, something like: category = models.ForeignKey(ProductCategory, null=False) I would like to also somehow disallow deletion of the root ProductCategory node (as there is no category that linked products could be assigned to). Is there any neat way to achieve these? -
How to have two separate query-sets under the same class based view
I am trying to have a friends list of all the people who are connected to you with href that sends you to their profile but get: `Reverse for 'view_profile_with_pk' not found. 'view_profile_with_pk' is not a valid view function or pattern name. in the HTML traceback details i get : return render (request, self.template_name, args) Views.py class ViewProfile(generic.ListView): model = Post template_name = 'accounts/profile.html' def view_profile(request, pk=None): if pk: user = User.objects.get(pk=pk) else: user = request.user kwargs = {'user': request.user} return render(request, 'accounts/profile.html', kwargs) def get(self, request): users =User.objects.all() object_list= Post.objects.filter(owner =self.request.user).order_by('-timestamp') args ={'object_list':object_list,'users':users} return render (request, self.template_name, args) urls.py # profilepage url(r'^profile/$', views.ViewProfile.as_view(), name='view_profile'), # profilepage url(r'^profile/(?/P<pk>\d+)/$', views.ViewProfile.as_view(), name='view_profile_with_pk'), profile.html <div class="col-md-4"> <h1>Friends</h1> {%for user in users %} <a href="{% url 'accounts:view_profile_with_pk' pk=user.pk %}"> <h3>{{user.username}}</h3> </a> {%endfor%} </div> -
Validate parsed data in django admin
I am new in Django. I want to do a duplicate validation on a parsed data from uploaded xml file in Django admin. The admin uploads the xml file Extract the required data Validate if the data is already exist in the database If yes raise validationError If no then save the model. The above points are working except point 3. I am not sure where in admin.py should I check if the value already exists or not. Code from admin.py def save_model(self, request, obj, form, change): if not change: category_name, module_names = \ self.handle_uploaded_file(request.FILES['category_file']) ....................................................................... def handle_uploaded_file(self, f): #Upload the file .................................. return self.parse_uploaded_xml(name) def parse_uploaded_xml(self, name): tree = ET.parse(name) root = tree.getroot() category_name = root[0].text .............................. #return the category name and module name Code from models.py category_name = models.CharField(max_length=150, blank=False, null=True, default="", unique=True) module_name = models.TextField(blank=False, null=True) I want to use the following code for the validation def clean_category_name(self): if self.category_name and Category.objects.filter(category_name=self.category_name).exists(): raise ValidationError('This category is already in the database. Please supply a different category.') unique = true doesn't work while uploading the file/adding a category but it works when I edit a single category. Any help is highly appreciated. Thanks in advance. -
Django test client on an actual server
I'm testing deploying my first Django project using Apache. I use Django's test client to perform an "internal" GET from my own server, which worked OK locally, but not runnning on the actual server. The client ends up getting Django error messages, like Page not found (404) Request Method: GET Request URL: http://testserver/polls/forms/test1/ How can I get the client's GET to work on the actual server, having the it be performed on the actual http: //my_actual_server_name.something/polls/forms/test1 instead of "testserver" ? I tried setting SERVER_NAME= ‘my_actual_server_name.something’ in the settings.py file but that's not it. -
Django 504 Gateway Timeout and I can't understand why
In my production server I have the following setup: Debian 8 distro Supervisor 3.0 PostgreSQL 9.4 Nginx 1.6.2 uWSGI 2.0.15 (using socket, not port) RabbitMQ 3.3.5 Celery 4.1.0 Django 1.10.5 Django REST Framework 3.4.6 I have 4 Django projects on it, one of them is the biggest, and has 1 celery task. The problem is that sometimes every project returns 504 gateway timeout error (in the same moment), but I can't find the source of that problem! I check out logs and don't report errors; Sentry doesn't notify anything. I suppose that could be some endpoint in DRF that is slow and, with multiple concurrent requests, django or uwsgi go down... I try to restart supervisor process for the biggest django project when 504 is coming, and seems that it going fast for a little time, but it returns on 504 almost immediately. I try to monitor nginx and supervisor logs, but I can't see a high traffic of requests before the timeouts... so what can I do? How can I find the bottleneck? -
Why django-rest-framework doesn't display OneToOneField data - django
I want to setting up restful API in my site. I used django-rest-framework. When I get an object from database, it doesn't show related object. Below snippet is my first model (parent model): class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, related_name='profile',on_delete=models.CASCADE) name = models.CharField(max_length=30) family = models.CharField(max_length=50) and the below snippet is my second model (child model): class Klass(models.Model): title = models.CharField(max_length=50) description = models.CharField(max_length=500) teacher = models.ForeignKey(Profile,related_name='teacher', on_delete=models.CASCADE) university = models.CharField(max_length=50, blank=True, null=True) as you see in the second snippet, the teacher gets its value from Profile model. But in django-rest-framework API view, instead of displaying the teahcer's name, it displays the pk. The below snippets is my serializer and view: # serializer class KlassSerializer(serializers.ModelSerializer): class Meta: model = Klass fields = ('id', 'title', 'description', 'teacher') # view class KlassView(APIView): def get(self, request, pk=None): if pk is not None: klass = Klass.objects.filter(pk=pk).get() serializer = KlassSerializer(klass) return Response({'message': 'class get ', 'data': serializer.data,}) and this is the result: { "message": "class get ", "data": { "id": 13, "title": "ُThe First Class", "description": "Nothing for now!", "teacher": 2 } } How can I solve the problem? thanks -
How to call a function inside view.py
This is the current project stucture R6Scorextractor R6Scoreex migrations templates R6Scoreex header.html home.html __Init__.py settings.py urls.py views.py models.py apps.py admin.py tests.py R6Scorextractor __Init__.py settings.py urls.py manage.py R6Scorextractor/R6scoreex/urls.py from django.conf.urls import url from . import views from django.conf.urls import include urlpatterns = [ url(r'^$', views.index, name='index'), ] R6Scorextractor/R6scoreex/views.py # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.shortcuts import render from django.shortcuts import render from django.conf import settings from django.core.files.storage import FileSystemStorage # Create your views here. from django.http import HttpResponse import pdb; def index(request): return render(request, 'R6scoreex/home.html') def simple_upload(request): print "Entered simple_upload" if request.method == 'POST' and request.FILES['myfile']: myfile = request.FILES['myfile'] fs = FileSystemStorage() filename = fs.save(myfile.name, myfile) uploaded_file_url = fs.url(filename) return render(request, 'R6scoreex/home.html', { 'uploaded_file_url': uploaded_file_url }) return render(request, 'R6scoreex/home.html') R6Scorextractor/R6Scorextractor/url.py from django.conf.urls import url from django.contrib import admin from django.conf.urls import include urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'', include('R6scoreex.urls')), ] I just want to know how to call simple_upload inside views.py of R6scoreex module.How to write URL for it , server gives me 404 error when I went with the following url(r'^/simple_upload$/', views.simple_upload, name='simple_upload'), So what is the reason I am getting 404 error even after adding the above code what am I doing wrong here -
Parsing and saving Json response values - Django
I have a django project that sent a json request and now I am getting json back. There are certain values from the json reponse that I want to save into a model that I created that will store the information gathered. I couldnt find a way to parse the data and save the data that was taken... Here is a sample response that I am using which has information that I want to extract... { '_id':'..e154e57', '_links':{ 'self':{ 'href':'https://uat-api.synapsefi.com/v3.1/users/..002e154e57' } }, 'client':{ 'id':'..1026a34', 'name':'Charlie Brown LLC' }, 'doc_status':{ 'physical_doc':'MISSING|INVALID', 'virtual_doc':'MISSING|INVALID' }, 'documents':[ ], 'emails':[ ], 'extra':{ 'cip_tag':1, 'date_joined':1504774195147, 'extra_security':False, 'is_business':True, 'last_updated':1504774195147, 'public_note':None, 'supp_id':'123abc' }, 'is_hidden':False, 'legal_names':[ 'Hello McHello' ], 'logins':[ { 'email':'hello@synapsepay.com', 'scope':'READ_AND_WRITE' } ], 'permission':'UNVERIFIED', 'phone_numbers':[ '555-555-5555' ], 'photos':[ ], 'refresh_token':'..C1tdG8LPqF6' } sample peices of information I want are id, sip, supp, joined, refresh tocken -
Django NotImplementedError: annotate() + distinct(fields) is not implemented
I want to count the total number of specific values in the structure field. Fund.objects.all().exclude(structure__isnull=True).extra(select={'Structure': 'structure'}).values('Structure').annotate(total=Count('structure')).order_by('-total') But before I do, I want to apply distinct() function so that only the objects with distinct id will be used for the query. So i tried something like this: object_list = Fund.objects.all().distinct('id') object_list.exclude(structure__isnull=True).extra(select={'Structure': 'structure'}).values('Structure').annotate(total=Count('structure')) But I get the error: NotImplementedError: annotate() + distinct(fields) is not implemented. How can I achieve this? -
Data manipulation using python [2.7]
I have a code for iterating over data and finding the specific value. code: data={'Namelist': {'thomas': {'gender': 'male', 'age': '23'}, 'david': {'gender': 'male'}, 'jennie': {'gender': 'female', 'age': '23'}, 'alex': {'gender': 'male'}}, 'selectors': {'naming': 'studentlist', 'code': 16}} name_list = [name for name, person in dictionary['Namelist'].items() if person.get('age') == '23'] names=(', '.join(name_list)) print names this gives o/p as : thomas, jennie I am trying out for a scenario where I can store and o/p Thomas and jennie seperately in two different variables. for example: a=len(names) print a # output will be 2 so according to this value it should assign thomas to variable 'b' and jennie to variable 'c' and yield it so that I can use it in flask/django framework as a output -
DRF Serializer - Many to Many with through field, Object has no attribute
I have models with many-to-many relationships with a through model. I am trying to set up a DRF serializer to display this data, but I am getting an error message whenever I try to render the API. #models.py - simplified class Person(models.Model): first_name = models.CharField(max_length=250) last_name = models.CharField(max_length=250) status = models.IntegerField(choices=STATUS_CHOICES) village = models.ForeignKey(Village) gender = models.IntegerField(choices=GENDER_CHOICES) class Case(models.Model): summary = models.TextField() session = models.ForeignKey(Session, on_delete=models.CASCADE) case_type = models.ForeignKey(CaseType) court_type = models.IntegerField(choices=COURT_TYPES) verdict = models.ForeignKey(Verdict) litigants = models.ManyToManyField(Person, through='Litigant', related_name='litigants') class Litigant(models.Model): person = models.ForeignKey(Person, on_delete=models.CASCADE) case = models.ForeignKey(Case, on_delete=models.CASCADE) role = models.ForeignKey(Role) fine = models.ForeignKey(Money, null=True, related_name='fine') My serializers.py looks as such: #serializers.py - simplified class LitigantSerializer(FlexFieldsModelSerializer): class Meta: model = Litigant fields = ('id', 'person', 'case', 'role', 'fine') class CaseSerializer(FlexFieldsModelSerializer): litigants = LitigantSerializer(many=True, read_only=True) class Meta: model = Case fields = ('id', 'summary', 'session', 'case_type', 'court_type', 'verdict', 'litigants') class PersonSerializer(FlexFieldsModelSerializer): class Meta: model = Person fields = ('id','first_name', 'last_name', 'village', 'status', 'gender') My views.py is: #views.py - simplified. class PersonViewSet(FlexFieldsModelViewSet): queryset = Person.objects.all().order_by('village__name', 'last_name', 'first_name') serializer_class = PersonSerializer class CaseViewSet(FlexFieldsModelViewSet): queryset = Case.objects.all().order_by('session__village__name', 'session__date', 'court_type') serializer_class = CaseSerializer class LitigantViewSet(FlexFieldsModelViewSet): queryset = Litigant.objects.all().order_by('case__session__village__name', 'case__session__date', 'person__last_name', 'person__first_name') serializer_class = LitigantSerializer However, when I navigate to api/cases/ I receive the … -
How to send data from arduino gprs module to django application hosted on heroku?
I have a django web application hosted on heroku server, currently I am using the free package for hosting right now. I want to send data from arduino using SIM900L gprs module to the web application. I want to know if it is possible? I have searched for the solution but couldn't find a proper guide or example for it. My web application accepts the get request and updates values in database when url is entered however if the arduino sends data using the same url I get the following error; AT+CIPSTART="TipCP","https://.herokuapp.com",80 ERROR Any tested example or suggestions about what I am doing wrong or what I should be doing instead. -
How to go through two loops in django templates
Can anyone tell me what am I doing wrong in this code: {% for dayName in data %} <tr> <td>{{ dayName }}</td> {% for value in data.dayName %} <td>{{ value }}</td> {% endfor %} </tr> {% endfor %} data is an object containing arrays, for an instance: data['Sunday'] = [1 ,2 ,3] And all what I want to do is create two loops through that object. I will be thankful for each form of help, Thanks in advance -
Django - Authenticate doesn't add backend to user
I've created a signup form which although successfully creates a user fails to login as authenticate fails to assign a backend, even though user is then marked as is_authenticated=True Is there something incorrect in the way that I'm using authenticate? (note I'm using django all_auth but not sure if that has an impact here?) At login() it generated this error: ValueError:You have multiple authentication backends configured and therefore must provide the backend argument or set the backend attribute on the user. view: .... form = ProfileForm(request.POST) if form.is_valid(): user_profile, user = form.save() authenticate(request, user=form.cleaned_data['email'], password=form.cleaned_data['password1']) login(request, user) models.py class User(AbstractUser): def __str__(self): return self.username def get_absolute_url(self): return reverse('users:detail', kwargs={'username': self.username}) class UserProfile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL) TITLE_CHOICES = ( ..... ) title = models.CharField(max_length=5, null=True, choices=TITLE_CHOICES) date_of_birth = models.DateField() primary_phone = PhoneNumberField() EMPLOYMENT_CHOICES = ( (....,...) ) employment_status = models.CharField(max_length=35, choices=EMPLOYMENT_CHOICES) Profile form: class ProfileForm(allauthforms.SignupForm): title = FieldBuilder(UserProfile, 'title', ) first_name = forms.CharField(max_length=30) last_name = forms.CharField(max_length=30) date_of_birth = FieldBuilder(UserProfile, 'date_of_birth', widget=SelectDateWidget()) primary_phone = FieldBuilder(UserProfile, 'primary_phone') employment_status = FieldBuilder(UserProfile, 'employment_status') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields["employment_status"].choices = [("", "---- Select your Employment Status ----"), ] + list( self.fields["employment_status"].choices)[1:] def save(self, *args): data = self.cleaned_data user = User.objects.create_user( username=data['email'], email=data['email'], password=data['password1'], first_name=data['first_name'], … -
Bootstrap 4 with Django not displaying properly
I'm trying to set-up Django to work with Bootstrap. I can't seem to get it to work properly, and I'm not sure what I'm doing wrong. To start, I'm just displaying a panel. It should look like this example from W3Schools. Instead, it looks like this: Here's what my generated HTML looks like: <!DOCTYPE html> <html lang="en"> <head> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous"> <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.11.0/umd/popper.min.js" integrity="sha384-b/U6ypiBEHpOf/4+1nzFpr53nxSS+GLCkfwBdFNTxtclqqenISfwAzpKaMNFNmj4" crossorigin="anonymous"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/js/bootstrap.min.js" integrity="sha384-h0AbiXch4ZDo7tp9hKZ4TsHbi047NrKGLO3SEJAg45jXxnGIfYzk4Si90RDIqNm1" crossorigin="anonymous"></script> </head> <body> <div class="container"> <h2>Basic Panel</h2> <div class="panel panel-default"> <div class="panel-body">A Basic Panel</div> </div> </div> </body> </html> It seems like some styling is being applied, since if I remove the stylesheet <link>, it seems to change the styling. On the Bootstrap site, it mentions that incomplete styling could be due to the DOCTYPE declaration, but as far as I can tell, I got that correct. I assume I'm making some relatively obvious mistake here. -
Django Applying Filters To Reload DataTable
So I have a couple of filters that user can apply to alter the information displayed in a Table. I have an Ajax call that gets triggered whenever a user clicks on a one of these filters: $.ajax({ url: '/fund_monitor/fund_directory', type: 'GET', data:JSON.stringify({ filter_dict: filter_dict }), success: function (data) { } }); Pretty simple stuff. Next my Class Based View will serve this Ajax Call. def get(self, request, *args, **kwargs): filtered_ids = [] if request.is_ajax(): #filter_dict = request.GET.getlist('filter_dict') request_data = json.dumps(request.GET) request_data = json.loads(request_data) for each in request_data: each = json.loads(each) # Just for parsing for key, value in each['filter_dict'].items(): if key == 'Structure': objects = Fund.objects.filter(structure__in=value).values('fund_account_id').distinct() for fund_account_id in objects: filtered_ids.append(fund_account_id['fund_account_id']) elif key == 'Fund Class': objects = Fund.objects.filter(fund_class__in=value).values('fund_account_id').distinct() for fund_account_id in objects: filtered_ids.append(fund_account_id['fund_account_id']) elif key == 'Designated Broker': objects = Fund.objects.filter(designated_broker__in=value).values('fund_account_id').distinct() for fund_account_id in objects: filtered_ids.append(fund_account_id['fund_account_id']) filtered_ids = set(filtered_ids) context = self.get_context_data(filtered_ids, **kwargs) self.template_name = 'fund_monitor/fundaccount_table_list.html' return self.render_to_response(context) context = self.get_context_data(**kwargs) return self.render_to_response(context) So after I collected all the ids that I want to be displayed in the table, I pass it to the get_context_data function which takes all these ids and obtains the required information based on the ids. def get_context_data(self, filtered_ids=None, **kwargs): context = super(__class__, self).get_context_data(**kwargs) … -
Not rendering a list of dicts in JSON response Django 1.10
def geoJSON_view(object_list): response = get_map_data(object_list) return JsonResponse(response, safe=False) Response is a dict that's been validated on several sites in the format: { "type": "FeatureCollection", "features": [ { "type": "Feature", "properties": { "name": "KMSP" }, "geometry": { "type": "Point", "coordinates": [ -93.22177777777777, 44.881972222222224 ] } }, { "type": "Feature", "properties": { "name": "KPHX" }, "geometry": { "type": "Point", "coordinates": [ -112.01158333333333, 33.43427777777777 ] } }, { "type": "Feature", "properties": { "name": "KDEN" }, "geometry": { "type": "Point", "coordinates": [ -104.67316666666667, 39.861666666666665 ] } } ] } and this is what's being sent to the url: { type: "FeatureCollection", features: [ ] } type(response) = dict I get the same result when trying it with HttpResponse Also, I've tried https://docs.djangoproject.com/en/1.11/ref/contrib/gis/serializers/#module-django.contrib.gis.serializers.geojson but geojson apparently doesn't exist Any ideas? -
What is the a performance cost of Django's unqiue_together feature
To me it seems like there would be a lot of processing or searching when using more complex unique_together tuples. It seems like the better option would be to strictly handle uniqueness when creating records in a database. Does anyone happen to know what the costs are to using unique_together especially if they involve more complex tuples? I currently have a model that I will likely need to switch from index_together = unique_together = (('a', 'b'), ('a', 'c', 'd')) to index_together = unique_together = (('a', 'b', 'e'), ('a', 'c', 'd', 'e')) -
GeoDjango: Can't save a model with PointField(), Error: SpatialProxy (POINT) with value of type: <class 'users.models.Point'>
The idea is to integrate Google Maps instead of the default map for GeoDjango v1.11.5 PointField(). Currently, in my models.py class Teacher(models.Model): user = models.OneToOneField(User, on_delete=models.PROTECT, related_name='Teacher') placename = models.CharField(blank=True,max_length=255) latitude = models.FloatField(blank=True, null=True, verbose_name='Latitude') longitude = models.FloatField(blank=True, null=True, verbose_name='Longitude') location = models.PointField(blank = True, null=True, srid=4326) objects = models.GeoManager() def save(self, *args, **kwargs): self.location = Point(self.longitude, self.latitude) super(Teacher, self).save(*args, **kwargs) # Call the "real" save() method. However, when I click save after I manually add the long and lat, I get: TypeError at /admin/users/location/add/ Cannot set Location SpatialProxy (POINT) with value of type: -
django-easy-pdf making the table header show up on each page
Is there a way in django-easy-pdf to include the table header on each page of the print? <table> <tr> <th> First Name </th><th> Last Name</th> <!--I want this on each page of pdf --> </tr> {% for employee in employees %} <tr> <td> {{ employee.first_name}} </td><td> {{ employee.last_name}}</td> </tr> {% endfor %} </table> -
Django weighted percentage
I'm trying to calculate a weighted percentage in a Django query. This is an example of what my data looks like: id start_date agency_id area_id housetype_id no_of_changed price_change_percentage total 6716 2017-08-26 11 1 1 16 -0.09 35 6717 2017-08-26 11 1 3 44 -0.11 73 6718 2017-08-26 11 1 4 7 -0.1 12 6719 2017-08-26 11 1 5 0 0 4 6720 2017-08-26 11 1 6 0 0 1 6721 2017-08-26 21 1 1 0 0 1 6722 2017-08-26 34 1 1 0 0 1 6723 2017-08-26 35 1 1 0 0 1 6724 2017-08-26 38 1 1 0 0 1 and this is my current code: from django.db.models import F, FloatField, ExpressionWrapper from app.models import PriceChange def weighted_percentage(area_id, date_range, agency_id, housetype): data = PriceChange.objects.filter(area_id=area_id, start_date__range=date_range, agency_id=agency_id, ) if housetype: data = data.filter(housetype=housetype) \ .values('start_date') \ .annotate(price_change_total=ExpressionWrapper((F('price_change_percentage') * F('no_of_changed')) / F('total'), output_field=FloatField())) \ .order_by('start_date') else: # what to do? pass x = [x['start_date'] for x in data] y = [y['price_change_total'] for y in data] return x, y I figured out how to do the calculation when housetype is defined and I only need to data from one row. I can't figure out how to done when I need to calculate …