Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
My django template file is not loading css static file
I am New to django and I have a homepage html file in django template which I want to load with css. <title> AOL </title> <meta charset="utf-8" /> {% load staticfiles %} <link rel="stylesheet" href="{% static 'home/css/myfile.css' %}" type = "text/css"/> This is my settings.py STATIC_URL = '/static/home/' Still the hmtl file is not loading it.. Help would be appriciated. My directories are as such webapp -migrations -static -home -css -myfile.css -templates -home -myfile.html -
get requests in urls.py django
i'm trying to authorize applications that send request to my website with post method in the first urls.py More Explanation i store some tokens in database for applications that want to use my site's advantages like OAuth. when applications send request, they must send token too. so i don't want to authorize token in every view. i want to authorize token in first urls.py that request goes at the first step or if you have better suggestions i'll be glad with it here is what i've done i've created two apps in my project, system and core. in core app, i made ApplicationTokens model with two fields token and owner. i thought it's better this way well i should say that i dont want to use prepared apps like OAuth comments are welcome Thanks -
Excluding a list of a user's friends from the User.objects.all() queryset in django
In one of my views I override the get_queryset(self) method in order to return a list of users that excludes the friends of the user making the request and the same user. This is what my code looks like: def get_queryset(self): all_users = User.objects.all() user_friends = Friend.objects.friends(self.request.user) # Filter all_users to exclude all elements of the user_friends queryset. # Filter all_users to exclude the current user making the request. # Return the filtered queryset. I am using the django-friendship library to handle friend requests and users being friends. In the getting data about friendship section, it says to get a list of all a user's friends all that needs to be done is Friend.objects.friends(request.user). I am unsure if this would return a list of Friend instances or of User instances. The source code for the Friend model is here. In either case, how would I filter the queryset all_users to exclude all elements of the list user_friends. -
Some advices in creating json-api with django
I'm creating json-api server for my movie service and I'm looking for most simple way. I don't have any troubles. I'm just want to know your opinion and get some advices. For example, I have the following code on the client side: import requests import json params_dict = {'movie_data': {'name': 'Gifted', 'duration': 107, 'description': 'Description...', 'countries': ['USA', 'Canada', '...']}, 'user_id': 3416} params = {'params': json.dumps(params_dict)} r = requests.get('http://127.0.0.1:8000/api/test_request', params=params) print(r.json()) input() And following code on the views.py: def test_request(request): json_response = json.loads(request.GET.dict()['params']) print(json_response) return JsonResponse(json_response) So, json_response quite normal json-formatted thing: {'movie_data': {'name': 'Gifted', 'duration': 107, 'description': 'Description...', 'countries': ['USA', 'Canada', '...']}, 'user_id': 3416} Now I'm looking for method to serialize media data, but it's not important. So, what do you think about this method? Will this affect security or something else? What are its disadvantages and advantages compared to the special libraries like: hyp; django-rest-framework-json-api; jsonapi; etc. -
Replacing list values django
I have: a=[['2017-07-25 23:48:36+00:00', 48L], ['2017-07-25 23:53:36+00:00', 53L], ['2017-07-25 23:54:36+00:00', None]] I need to leave the timestamp as it is. But change the other values as 'None' to '0' and else multiply by 0.1. So it becomes: formatted_a = [['2017-07-25 23:48:36+00:00', 4.8L], ['2017-07-25 23:53:36+00:00', 5.3L], ['2017-07-25 23:54:36+00:00', 0]] I have code in view.py like this: def replace(a): return [0 if y is None else 0.1*y for x, y in a] formatted_a = list(replace(a) for a in a) I am getting ValueError:ValueError: too many values to unpack -
How to restrict the deletion of PSQL table rows in Django?
I'm working on a project using Django 1.9 + django.db.backends.postgresql_psycopg2 On one model I have a m2m relationship: class School(models.Model): ... admins = models.ManyToManyField( User, verbose_name=_("admins"), related_name="admins", blank=True ) ... This, of course, ends up creating a "school_admins" table on the DB. with 3 columns (id, school_id, user_id) I need to restrict the deletion of rows on this table so they only can be deleted from a specific endpoint. I tried to do this by adding a m2m_changed signal but there is a limitation that makes this impossible Any ideas on how to do this? -
Python Social Auth User without email
There is one problem. I need users` emails to register a new one in my application. In other words, email is required for users. But there are Facebook accounts that do not have an email attached. So, in a result, we get an error. I see one solution: when we recognized that Facebook returned us data without Facebook, show a form where a user should enter his email, he wants to use in the application. And then we can continue register process. But how to realize this? Actually, I have no idea. What about you? Thanks -
In Django 1.10 authentication with allauth, login_required decorator does not work
I have just started learning Django 1.10. In doing so, I would like to implement authentication functionality with all-auth package and login_required decorator. Here is the snippet code of urls.py file I have written. from django.conf import settings from django.conf.urls import url, include from django.conf.urls.static import static from django.contrib import admin from profiles import views as profiles_views from contact import views as contact_views urlpatterns = [ .... url(r'^profile/$', profiles_views.userProfile, name='profile'), url(r'^accounts/', include('allauth.urls')), ] This is the code of views.py file. from django.contrib.auth.decorators import login_required from django.shortcuts import render .... @login_required def userProfile(request): user = request.user context = {'user' : user} template = "profile.html" return render(request,template,context) Here is the settings for allauth. LOGIN_URL = 'accounts/login' LOGIN_REDIRECT_URL = '/' ACCOUNT_AUTHENTICATION_METHOD = "username_email" ACCOUNT_CONFIRM_EMAIL_ON_GET = False ACCOUNT_EMAIL_CONFIRMATION_ANONYMOUS_REDIRECT_URL = LOGIN_URL ACCOUNT_EMAIL_CONFIRMATION_AUTHENTICATED_REDIRECT_URL = None ACCOUNT_EMAIL_CONFIRMATION_EXPIRE_DAYS = 3 ACCOUNT_EMAIL_REQUIRED = False ACCOUNT_EMAIL_VERIFICATION = None ACCOUNT_EMAIL_SUBJECT_PREFIX = "My subject : " ACCOUNT_DEFAULT_HTTP_PROTOCOL = "http" ACCOUNT_LOGOUT_ON_GET = False ACCOUNT_LOGOUT_REDIRECT_URL = '/' ACCOUNT_SIGNUP_FORM_CLASS = None ACCOUNT_UNIQUE_EMAIL = True ACCOUNT_USER_MODEL_USERNAME_FIELD = "username" ACCOUNT_USER_MODEL_EMAIL_FIELD = "email" ACCOUNT_USERNAME_MIN_LENGTH = 5 ACCOUNT_USERNAME_BLACKLIST = [] ACCOUNT_USERNAME_REQUIRED = True ACCOUNT_PASSWORD_INPUT_RENDER_VALUE = False ACCOUNT_LOGIN_ON_EMAIL_CONFIRMATION = True As you can see, I use login_required decorator to userProfile function. So if I go to localhost/profile on the browser … -
How to put "python functions" into HTML files in a Django Project
Working in a Django Project. I have an index.html file with a variable called "todas_academias", which is a list of models classes that I've created. Directory: FKSC/ac_filiados/templates/ac_filiados/index.html {% for academia in ordenar(todas_academias) %} <td>{{ academia.nome_academia }}</td> <td>{{ academia.estado }}</td> <td>{{ academia.cidade }}</td> <td>{{ academia.professor }}</td> <td>{{ academia.num_alvara }}</td> {% endfor %} And I created a function called "ordenar" in a python file in another directory. Directory: FKSC/ac_filiados/functions.py You DON'T NEED to understand what this function does. def ordenar(todas_academias): lista = [] for academia in todas_academias: lista = lista + [academia.num_alvara] nova_list = lista.sort() nova_lista_academias = [] for reg in nova_list: for academia in todas_academias: if reg == academia.num_alvara: nova_lista_academias = nova_lista_academias + [academia] return nova_lista_academias Now, I just want to use the "ordenar()" function in the index.html file, as I tried to use, but it didn't work. 1) Do I need to import the "ordenar" function before using it? If so, How do I import it? 2) Should I've placed the "ordenar" function in views.py? 3) Or, is there a specific way of using this kind of functions in HTML files? -
Django: tracking via signals and cascade delete
I'm using django signals to track user actions (profile/subscription updates) on site. And have the following models.py: class Customer(models.Model): user = models.OneToOneField(to=User, null=True, blank=True) ... class Subscription(models.Model): customer = models.ForeignKey('Customer', null=True, related_name='subscriptions') ... class Activity(models.Model) source = models.ForeignKey('Customer', null=True, related_name='subscriptions') ... and following signal: @receiver(post_delete, sender=Subscription, dispatch_uid='track_sub_post_delete') def track_subscription_delete(sender, instance, *args, **kwargs): extra = {'sub': instance, 'action': 'deleted', 'old': instance.__str__()} tracker = ActivityTracker(target=instance.customer, mode='subscription', extra=extra) tracker.save() When I'm trying to delete any customer/user (on_delete=models.CASCADE): all activities are deleted successfully activity delete tracker logs it with source = customer customer is deleted activity object still has reference on customer (which is already deleted) and this causes django to crush with smth like Exception Value: insert or update on table "dashboard_activity" violates foreign key constraint "smth_fk_accounts_source_id" DETAIL: Key (source_id)=(1) is not present in table "dashboard_customers". (can't find exact error msg right now) Is there any way to prevent this? (other than using on_delete=SET_NULL and manually deleting related objects via signal) -
Mocking Methods within Classes
I've read a lot of information online about mocking entire classes. However, I have a class with multiple methods; for example: class A(): def methoda(param1, param2): do things return thing def methodb(param3): do things (including something calling methoda) How can I mock out methoda in a testing file to return a desired value so that I can test methodb? I don't want to mock out the entire class. What I've tried doing: from mock import patch, mock, MagicMock from sourceA.models import ClassName from django.test import TestCase class ClassTest(TestCase): @patch('sourceA.models.ClassName.methodA') def test_method(self, mock_method_return): mock_method_return.return_value = 10 instance = ClassName() instance.methodB #METHOD B CALLS METHOD A; I want method A to return 10 print "OUTPUT", instance.FIELDA #Debug Tool - Field A is modified by Method B, based on the return value of method A assert instance.FIELDA == 10 I have also tried this: class ClassTest(TestCase): @patch('sourceA.models.ClassName.methodA', return_value=10) def test_method(self, mock_method_return): instance = Mock(spec=ClassName()) instance.methodB #METHOD B CALLS METHOD A; I want method A to return 10 ------ OR instance methodB = MagicMock(return_value=10) and then instance.MethodB print "OUTPUT", instance.FIELDA #Debug Tool - Field A is modified by Method B, based on the return value of method A self.assertEqual(instance.FIELDA, 10) I'm not sure what … -
unhashable type when redirecting back to the website using python-social-auth in Django
I'm trying to add a social media authentication to a website using Social-auth-app-django. So I've created different apps for the most popular social media websites (Facebook, Twitter, Google+), and have set the callback url there. But I'm coming across an error when I'm redirected back to the website from say Facebook: TypeError at /oauth/complete/facebook/ unhashable type: 'slice' Exception Location: | /usr/local/lib/python3.5/site-packages/social_core/backends/base.py in run_pipeline, line 105 What might cause this error? -
ManyToMany relationship in django models
I'm trying to add relation between three table with manyToMany relationship. I'm learning python and new for Django framework. For requirement, An user can add a project and he also can add permission for view for another user. It means an user can have multiple projects and a project also have multiple user. User model is default user model of django. and the project model is: Projects/model.py from django.db import models from django.contrib.auth.models import User # Create your models here. class Projects(models.Model): project_title = models.CharField(max_length=255) description = models.TextField(blank=True) privacy = models.SmallIntegerField(default=1) # 1 for public, 2 for private status = models.SmallIntegerField(default=1) #1 for active, 2 for deactive, 3 for delete, 4 for depricated created_at = models.DateTimeField('date published', blank=True, default=False) users = models.ManyToManyField(User, through="UserProjects") class UserProjects(models.Model): user = models.ForeignKey(User,blank=True, default=False) project = models.ForeignKey(Projects,blank=True) owner = models.SmallIntegerField(default=1) It's not working. When i'm add a project is produce some error.. Traceback (most recent call last): File "C:\Users\Jitendra\AppData\Local\Programs\Python\Python35-32\lib\site-pac kages\django\core\handlers\exception.py", line 41, in inner response = get_response(request) File "C:\Users\Jitendra\AppData\Local\Programs\Python\Python35-32\lib\site-pac kages\django\core\handlers\base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\Jitendra\AppData\Local\Programs\Python\Python35-32\lib\site-pac kages\django\core\handlers\base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "E:\Programs\Python\RestClient\Projects\views.py", line 29, in add p.save() File "C:\Users\Jitendra\AppData\Local\Programs\Python\Python35-32\lib\site-pac kages\django\db\models\base.py", line 806, in save force_update=force_update, … -
AttributeError: module has no attribute 'navigationview'
I am trying to get the view for navigation.html working in django but I'm getting the error "AttributeError: module 'ddapp.core.views' has no attribute 'navigationview'" The core folder houses my views.py. The other views worked before I add the navigation view. Below is my code. Any help would be greatly appreciated. urls.py: from django.conf.urls import url, include from django.contrib import admin from django.contrib.auth import views as auth_views from ddapp.core import views as core_views urlpatterns = [ url(r'^$', core_views.home, name='home'), url(r'^login/$', auth_views.login, {'template_name': 'login.html'}, name='login'), url(r'^logout/$', auth_views.logout, {'next_page': 'login'}, name='logout'), url(r'^signup/$', core_views.signup, name='signup'), url(r'^oauth/', include('social_django.urls', namespace='social')), url(r'^admin/', admin.site.urls), url(r'^navigation/', core_views.navigationview, name='navigation'), ] views.py: from django.contrib.auth.decorators import login_required from django.contrib.auth import login, authenticate from ddapp.core.forms import SignUpForm from django.shortcuts import render, redirect @login_required def home(request): return render(request, 'home.html') def signup(request): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): user = form.save() user.refresh_from_db() username = form.cleaned_data.get('username') user.profile.birth_date = form.cleaned_data.get('birth_date') user.save() raw_password = form.cleaned_data.get('password1') user = authenticate(username=username, password=raw_password) login(request, user) return redirect('home') else: form = SignUpForm() return render(request, 'signup.html', {'form': form}) def navigationview(request): return render(request, 'navigation.html') -
What is the Django command to access a related attribute in a many-to-many relationship (not related_name)
In Django, I have a model called Articles. Each article has an attribute called "comments_on". This attribute has a many-to-many relationship with all the articles that it criticizes. The related_name for this attribute is "commented_on_by". This means that if article1 criticizes article2, then article2.commented_on_by will point to article1. My question is how do I get access to article2 from article1? In other words, I'd like to write something like article1.[something] to access article2. Thank you. -
Ajax Call with JS from Python
I have simple django project name Ajax .And i installed only one app for this project name Promocode . My problem in this project is Ajax call between js and python. I can't handle Succes with ajax call function . Error: function () result i got. I know i mistake in urls.py in promocode app and url mapping in ajax call function but i can't solve this. Please help me :) My main urls.py file is : from datetime import datetime from django.conf.urls import url,include import django.contrib.auth.views urlpatterns = [ url(r'^', include('promocode.urls'))] My promocode app urls.py file is : from django.conf.urls import url, include from . import views urlpatterns = [ url(r'^$', views.index,name='index'), url(r'^$', views.extract_json)] My views.py file is : from django.shortcuts import render import json from suds.client import Client as Client from django.http.response import HttpResponse def index(request): return render(request,'promocode/index.html') def get_result_by_code(promocode): url = "http://service.emobile.az:8080/ws-loyalty- program/cp/loyaltyprogram.wsdl" client = Client(url) result = client.service.loyaltyProgramCalculate( amount=1000, authKey='testaede35740f2b9d2248b0ab6b878', identicalCode=promocode, terminalCode=2148) if str(result[2]) == "SUCCESS": status = 1 else: status = 0 return status def extract_json(request): data = json.loads(request.body) status = get_result_by_code(data['4545']) result = dict( status=status, message='Result Succesfully' ) return HttpResponse(json.dumps(result), mimetype='application/json') And my index.html file is : <!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"> </script> … -
Group query elements by by same name in django
I am stuck on this task. My query output is as follows (when list() is used): days=[{'day':1,'do':'paint'},{'day':2,'do':'paint'},{'day':3,'do':'Dry'},{'day':4,'do':'Fubrish'},{'day':5,'do':'Fubrish'},{'day':6,'do':'paint'}] I basically want to loop thru each and see if there are same 'do' consecutively and store the total number of found occurance. E.g. Day 1 and 2, the user is advised to do painting. Day 3 he does Drying and the next 2 days to Fubrish then again paint. I want an output that will basically say: paint:2 dry:1 fubrish:2 paint:1 I did play on my jupyter but it is errorful: tasks={} total=len(days) for i in range(0,total): day=days[i]['day'] do=days[i]['do'] if i==0: tasks[do]=1 else: if i+1<total: if days[i+1]['do']==do: #the next one is same as current one tasks[do]=len(tasks)+1 else: if tasks.get(do,None)!=None: tasks[do]=len(tasks)+1 else: tasks={} tasks[do]=1 -
Saving a Cloudinary object to a Django Model
I have a model: from cloudinary.models import CloudinaryField class Image(models.Model): image = CloudinaryField('image') And an object that I received from Cloudinary. It was given to me by Cloudinary after I uploaded an image, and I passed it back to my server: {'etag': ['***'], 'version': ['***'], 'public_id': ['***'], 'type': ['upload'], 'signature': ['***'], 'created_at': ['2017-07-28T15:54:17Z'], 'secure_url': ['https://res.cloudinary.com/***/***.png'], 'height': ['353'], 'format': ['png'], 'resource_type': ['image'], 'url': ['http://res.cloudinary.com/***/image/upload/***/***.png'], 'width': ['684'], 'bytes': ['133509']} I can't seem to save it to my model. I have tried both saving it directly and putting it through the CloudinaryJsFileField form in Cloudinary's documentation. Neither seems to work. The form laments that "No File Was Selected" and the model.create() effort complains of a missing property. Does anyone know how to save Cloudinary objects to the Django database? -
How to create a global variable in django template?
I'm doing a loop inside my template, well, i want verify if my actual object is equal the object that comes before this. This is my tamplate code: {% for i in format_data %} <li> {% with first=i %} {{forloop.counter}} {% if forloop.counter == 1 %} <table class="format-table"> <tr> <td data-format-id="{{i.format_name.id}}">{{i.format_name}}</td> <td>{{i.field_name}}</td> {% if i.field_format_data %} <td>{{i.field_format_data}}</td> {% else %} <td>Campo não preenchido</td> {% endif %} </tr> </table> {% elif second == first %} <table class="format-table"> <tr> <td>{{i.field_name}}</td> {% if i.field_format_data %} <td>{{i.field_format_data}}</td> {% else %} <td>Campo não preenchido</td> {% endif %} </tr> </table> {% endif %} {% endwith %} {% with second=i %} {% endwith %} </li> {% endfor %} What I want is set a variable in the final of the loop that receive this actual object and in the next time that loop works, verify if the actual object is equal the last -
GIF won't load in Safari but runs in Chrome
So after getting some help in my loading animation problem I decided to use a GIF. Now the issue is that when I keep display to show in the ID for the GIF it runs in Safari but when i change that to none it stops working in Safari when the required code is executed. Client requirement is that the GIF should only run when the upload button is clicked to upload a selected file. Now I am not sure if this has become a jQuery problem or it's a CSS problem. My Html Code; {{ form.photo1 }} <div id="spinnerr" ><img id="img-spinner" src="{{ STATIC_URL }}img/pacman_orange.gif" alt="Loading"/>loading</div> <input type="submit" class="UploadBtn btn bl cl bco mbs mts" style="border-color:#f57c00;" value="Upload"> My CSS code; #spinnerr { display: none; font-size: 20px; font-family: serif; color: #00C853; } .UploadBtn, .p { display: show; } #overlay { display: none; position: fixed; height: 100%; width: 100%; background: transparent; } My jQuery code; $(document).ready(function() { $(document).on("click", ".UploadBtn", function(event) { $(".p").each(function(file) { if ($(this).val()) { $("#spinnerr").show(); $("#overlay").show(); } }) }); }); Please note that 'p' class is for {{ form.photo1 }} which is written in Django. The GIF is working fine in Chrome but the requirement from the client is that … -
Cannot post data to django using jQuery
Im trying to post a simple json to a django server using jQuery. However when printing request.POST on the server Im not getting any of the data Im sending: This is my jquery: jQuery('.promote-form').submit(function () { //Check if we have more var $form = jQuery(this); var student_pk = jQuery(this).attr('student-pk'); // Check if there are checked checkboxes var $checked = jQuery(".checked"); if($checked.size()>0) { alert("checked"); var post_data = {}; var students_data = []; for (var i = 0; i < $checked.length; i++) { var $elm = jQuery($checked[i]); var $row = $elm.parent().parent().parent(); var row_student_pk = $row.attr("student-pk"); var $grade_selector = $row.find("#grade-selector-"+row_student_pk); if($grade_selector.is("select")){ var level_pk =$grade_selector.val(); } else{ var level_pk = $grade_selector.attr('value'); } students_data.push({ next_level_pk:parseInt(level_pk), student_pk:parseInt(row_student_pk) }); } if(jQuery(this).attr("approve")=="true"){ post_data.approve=true; post_data.students_data = students_data; alert("arppoobe27899889"); alert(JSON.stringify(post_data)); $form.post(Urls['promote-student'](student_pk), post_data); } else{ alert("reprobe"); post_data.students_data = students_data; $form.post(Urls['promote-student'](student_pk), post_data); } }); what I do on the django view is simply: print request.POST but the data is: <QueryDict: {u'csrfmiddlewaretoken': [u'y2IJv5VqEIodPdazhJBCj8ciRvgZTGZGtzfyGIG7ZcmaOroQ7uwGzh7w72QOvOso'], u'approve': [u'true']}> I suspect the data is being sent is the one that is on the original html template. But I want to add the data on JSON object I build using the Jquery function. Can anyone help me see my error? -
mysql table with many records and new index still slow
I have the following table with a little less than 600,000 records: CREATE TABLE `organization` ( `id` int(11) NOT NULL AUTO_INCREMENT, `company_name` varchar(255) DEFAULT NULL, `uuid` varchar(255) DEFAULT NULL, `created_at` varchar(255) DEFAULT NULL, `updated_at` varchar(255) DEFAULT NULL, PRIMARY KEY (`id`), KEY `org_company_name_7467253` (`company_name`) ) ENGINE=InnoDB AUTO_INCREMENT=589816 DEFAULT CHARSET=utf8mb4; The table was running slow so I created an index on company_name: CREATE INDEX `org_company_name_7467253` ON `organization` (`company_name`); I am doing several queries like the following that are taking around 30 seconds each: for e in Entity.objects.all(): #around 2000 records - select * from entities if Organization.objects.filter(company_name__icontains=e.name): #600,000 records - select * from organizations where company_name = entity.name print 'contains organization' Is there anything I can do to speed this up? -
Django CMS CKeditor
Can anyone tell me how I restrict the editor to only allow h1 and h2 under the Format attribute in the CKEditor: CKEDITOR_SETTINGS_TITLE = { 'language': '{{ language }}', 'toolbar_HTMLField': [ ['Format'] ] } -
GeoDjango: Distance Object is not serializable
I am just learning the geo-django. I can find out the distance of all places from a point. But when I use .values method to the annotated distance field, I am getting TypeError: Object of type 'Distance' is not JSON serializable Here is my code snippets #models.py import uuid from django.contrib.gis.db import models from django.contrib.gis.db.models.functions import Distance from django.contrib.gis.geos import Point class PlaceManager(models.GeoManager): def get_queryset(self): qs = super(PlaceManager, self).get_queryset() qs = qs.annotate( latitude=models.ExpressionWrapper(models.Func('position', function='ST_X'), output_field=models.FloatField()), longitude=models.ExpressionWrapper(models.Func('position', function='ST_Y'), output_field=models.FloatField()), ) return qs.distinct() def nearby_places(self, lat, lng): p = Point(lat, lng, srid=4326) qs = self.get_queryset() qs = qs.annotate( distance=Distance('position', p) ) return qs.order_by('distance').distinct() class Place(models.Model): id = models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, db_index=True) position = models.PointField() address = models.TextField(default=None, null=True, blank=True) objects = PlaceManager() def __str__(self): return '{},{}'.format(self.position.x, self.position.y) Now the code snippets I have is like this from rest_framework.views import APIView from rest_framework import status from rest_framework.response import Response class NearbyPlaces(APIView): def get(self, request): p = Place.objects.nearby_places(30.45, -90.43) p = p.values('distance', 'address', 'latitude', 'longitude') return Response(p, status=status.HTTP_200_OK) The value of p here is like this <GeoQuerySet [{'distance': Distance(m=7596021.71574835), 'address': 'New York City, New York','latitude': 13.4586, 'longitude': 45.6789}]> So all I needed here is 'distance': 7596021.71574835 instead of 'distance': Distance(m=7596021.71574835) Any help on this? … -
Safely persisting django models with foreign keys
I am implementing the storage of one-to-many models through a view. The model structure is as follows: A DagRun model Many DagRunModel, which have a FK to a DagRun Many DagModelParam, which have a FK to a DagRunModel So as follows, I Create all the instances first, to make sure there are no errors, and only in the very end, I persist them using save(). But this returns django.db.utils.IntegrityError: NOT NULL constraint failed: [28/Jul/2017 11:56:12] "POST /task/run HTTP/1.1" 500 19464 And this is the code of how I create the models and persist them in the end def task_run(request): dag_task = None dag_tasks = DagTask.objects.filter(dag_id=request.POST["task"]) if len(dag_tasks) > 0: dag_task = dag_tasks[0] else: raise ValueError("Task name is not a valid dag id") dag_run = DagRun( dag_task=dag_task, database=request.POST["database"], table=request.POST["table"], label=request.POST["label"], features=request.POST["features"], user=request.user, date=timezone.now() ) dag_params = [] dag_models = [] models = json.loads(request.POST["models"]) for model in models: dag_run_model = DagRunModel( dag_run=dag_run, dag_model=model["name"] ) dag_models.append(dag_run_model) for param in model["params"]: dag_param = DagRunParam( dag_run_model=dag_run_model, dag_param=param["name"], param_value=param["value"] ) dag_params.append(dag_param) dag_run.save() for dag_model in dag_models: dag_model.save() for dag_param in dag_params: dag_param.save() If I instead decide to save them as I create them, this code works fine. So it looks like Foreign Keys can only be …