Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Detect any changes made to Django models
I have found myself in a situation where for several models say X, Y and Z, I would like to know when any change happens on them i.e. any create, update, delete. I have scoured the internet but all I get is libs on instance audit history. Is there any way to accomplish this inbuilt in django or even a custom solution/lib would be highly appreciated. -
CSRF token missing or incorrect AJAX / DJANGO
Can someone help me with this problem? I have list of tasks in my page. Every task has there own form where users can send comments. When I add new task AJAX update list of comments and then I try to send comment by form and it raise error : “CSRF token missing or incorrect”. In any other situation forms work well. I have {% csrf_token %} in my form. It seems like I need send CSRF in AJAX. Where I did mistake? Why it didnt work? JS: function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie !== '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = jQuery.trim(cookies[i]); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } var csrftoken = getCookie('csrftoken'); // TASK $(function () { var loadForm = function () { var btn = $(this); $.ajax({ url: btn.attr("data-url"), type: 'get', dataType: 'json', beforeSend: function () { $("#modal").modal("show"); }, success: function (data) { $("#modal .modal-content").html(data.html_task_form); } }); }; var saveForm = function () { … -
Django - sitemap file from google. How to serve this up?
So here is the problem. I have never used Django before but our company took over SEO for a site that was built with Django. I have sftp access to the site and cms login information. (we are not hosting this) I have a few questions: Do i need to install any software locally on my machine for any reason to modify the website? What I am talking about is a CLI or anything like that? (of course I have my IDE of choice - phpstorm) I am brand new to Django (and python) - this is my exposure and from my understanding there is typically a build process with Django - such as a dev staging and production site. I of course do not have a build process so I am working off of production. Is this even feasible with Django? The pressing issue is our SEO team wants me to replace the sitemap with one generated from the google search console. I have read through the Django documentation and I learned that the sitemaps are being generated through a class of some sort. See: # urls.py from django.contrib.sitemaps import FlatPageSitemap, GenericSitemap # Sitemap config pages_sitemap = {'queryset': Page.objects.filter(status='active'), … -
POST method is not executing to fill form which saves values to database
I am a newbie to django framework and want to take values and save it to database. for this i used post method but when i check it is executing else part. I went through previous question on it but still found unsatisfying in my case. Code is as follow: #views.py from django.shortcuts import render, render_to_response from django.http import HttpResponse, HttpResponseRedirect from .models import student_info, history from django.shortcuts import get_object_or_404, render from .forms import info def index(request): return HttpResponse("Hello, world") def info(request): if request.method == "POST": the_form=info(request.POST or None) context={ "form": the_form } if form.is_valid(): form.save() else: return HttpResponse("It sucks") return render_to_response(request, 'info.html', context) #models.py from __future__ import unicode_literals from django.db import models # Create your models here. class student_info(models.Model): name=models.CharField(max_length=40, help_text="Enter Name") reg_no=models.IntegerField(help_text='Enter your reg_no', primary_key=True) email=models.EmailField(help_text='Enter email') def __str__(self): return self.name class history(models.Model): Reg_no=models.ForeignKey('student_info', on_delete=models.CASCADE) date=models.DateTimeField(auto_now=True) def was_published_recently(self): return self.date >= timezone.now() - datetime.timedelta(days=1) #forms.py from django import forms from .models import student_info, history class info(forms.ModelForm): name= forms.CharField(label= 'Enter name') reg_no= forms.CharField(label= 'Enter registration no.') email= forms.EmailField(label= 'Enter email') class Meta: model= student_info fields= ['name', 'reg_no', 'email',] #info.html <h1>Enter the details</h1> <form action="{% url 'auto:info' %}" method="post"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Go" /> </form> -
Django - BDD test can not find element by name
It seems like it can not find the element "firstname" which i have defined in forms. Something i'm missing or have misunderstood? Still a newbie and really appreciate your help, folks! Creating test database for alias 'default'... Feature: Add member Scenario Outline: Member succesfully added -- @1.1 Members Given a form ... passed in 1.913s When i fill in "foo","bar","fb@gmail.com","female","1990-02-01","2017-01-01","2017-06-03" ... failed in 1.867s Traceback (most recent call last): File "C:\...\lib\site-packages\behave\model.py", line 1456, in run match.run(runner.context) File "C:\...\lib\site-packages\behave\model.py", line 1903, in run self.func(context, *args, **kwargs) File "features\steps\step_add_member.py", line 39, in step_impl br.find_element_by_name('firstname').send_keys('foo') File "C:\...\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 378, in find_element_by_name return self.find_element(by=By.NAME, value=name) File "C:\...\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 784, in find_element 'value': value})['value'] File "C:\...\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 249, in execute self.error_handler.check_response(response) File "C:\...\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 193, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.NoSuchElementException: ***Message: {"errorMessage":"Unable to find element with name 'firstname'"***,"request":{"headers":{"Accept":"application/json","Accept- Encoding":"identity","Connection":"close","Content-Length":"92","Content-Type":"application/json;charset=UTF-8","Host":"127.0.0.1:40945","User-Agent":"Python http auth"},"httpVersio n":"1.1","method":"POST","post":"{\"using\": \"name\", \"value\": \"firstname\", \"sessionId\": \"341886b0-2447-11e7-b206-cf7b056db255\"}","url":"/element","urlParsed":{"anchor":"", "query":"","file":"element","directory":"/","path":"/element", "relative":"/element","port":"","host":"", "password":"","user":"","userInfo":"","authority":"","protocol":"","source": "/element","queryKey":{},"chunks":["element"]},"urlOriginal":"/session/341886b0-2447-11e7-b206-cf7b056db255/element"}} Screenshot: available via screen forms.py CHOICES = [('Female', 'Female'), ('Male', 'Male')] class RegForm(forms.ModelForm): first_name = forms.CharField( widget=forms.TextInput(attrs={'class': 'form-control', 'name': 'firstname', 'id': 'firstname'}), max_length=30, required=True) last_name = forms.CharField( widget=forms.TextInput(attrs={'class': 'form-control', 'name': 'lastname', 'id': 'lastname'}), max_length=30, required=True) email = forms.CharField( widget=forms.EmailInput(attrs={'class': 'form-control', 'name': 'email', 'id': 'email'}), required=True, max_length=75) reg_date = forms.DateField(widget=DateWidget(usel10n=True, bootstrap_version=3, attrs={'name': 'reg_date'})) … -
Deploying and viewing file contents
I've done (succefull) this tutorial: https://cloud.google.com/python/django/flexible-environment I have several questions: Can i view/edit files in browser? Under Tools->Development->Source code is nothing Suggested way to deploy is: gcloud app deploy but it always does full import. Is there a way to deploy delta? My local source code is not under GIT(was not mentoned in tutorial) -
Django form User is 'not-null' even though it's manually set
For ease of use, one of the fields in my form can have multiple foos, but eachfoo should/will create it's own record in the database. I have a ModelForm (MyForm) that captures the fields that are repeated for each instance of foo. Inside my views.py I copy MyForm for each instance of foo. All that is working, except for the bit where the logged in user is set as the submitter of the form. The following error is thrown: null value in column "submitter_id" violates not-null constraint. models.py class MyModel(models.Model): foo_bar = models.CharField(max_length=10) foo_baz = models.CharField(max_length=10) submitter = models.ForeignKey(User) forms.py class MyForm(forms.ModelForm): class Meta: Model = MyModel exclude = ['foo_bar','foo_baz','submitter'] views.py Note: obj is a dictionary of however many foos were entered into the form my_form = MyForm(request.POST) if my_form.is_valid(): for k,v in obj: copy = MyForm(request.post) copy.save(commit=False) copy.foo_bar = k copy.foo_baz = v copy.submitter = request.user # I have inspected this, and request.user is an instance of the User model copy.save() # <-- here is where I get the error above -
Django email attach method is not taking parameters right
My problem is that while sending email in django i want to attach a file. If i do it that way: email.attach("Random_name", uploaded_file.read()) it works and my email sends. But if instead of string "Random name" i put a variable there representing uploaded file name as: uploaded_file = request.FILES['stl_file'] uploaded_file_name = request.FILES['stl_file'].name email.attach(uploaded_file_name, uploaded_file.read()) the whole things blows up and i get a ValueError "need more than 1 value to unpack" for email.send() method. I have checked both variables upload_file and upload_file_name(by use of pdb tool) and both of them get the right value before calling attach method. Here is my view where i am trying to send the mail: def print(request): if request.method == 'POST': form = PrintForm(data=request.POST, request = request) if form.is_valid(): contact_name = request.POST.get('contact_name', '') contact_email = request.POST.get('contact_email', '') form_content = request.POST.get('content', '') supervisor = form.cleaned_data['supervisor'] template = get_template('threeD/email/contact_template_for_printing.txt') context = Context({ 'contact_name': contact_name, 'supervisor': supervisor, 'contact_email': contact_email, 'form_content': form_content, }) content = template.render(context) subject = "New message" email = EmailMessage( subject, content, contact_email, [supervisor], headers={'Reply-To': contact_email} ) if request.FILES: uploaded_file = request.FILES['stl_file'] uploaded_file_name = request.FILES['stl_file'].name email.attach(uploaded_file_name, uploaded_file.read()) email.send() messages.success(request, "Thank you for your message.") return redirect('/index/print/') else: form = PrintForm(request=request) context_dict = {} context_dict['printers'] = Printer.objects.all() … -
Django DataTables.net table can't display date data with NULL values
I have a table in my Django project which has some dates and other fields. Dates have displayed fine until now, but when adding a new column an error is thrown and the data does not display. The data type in SQL (date, null) and models.py (models.DateField(null=True)) is the same for existing date columns which work fine, and the new one which will not display. The migration process is also the same. NULL values should be allowed, but from what I can tell the only difference is that a high proportion of records in the new column (about 70%) are NULL, whereas there were no NULL values in the prior date columns. The error is the generic DataTables.net error saying that the parameter is unknown (anytime something goes wrong with a field, I get that same error regardless of the root cause). Here's the Python code: $(document).ready( function () { studentList = [] for (i = 0;i < advisor_portfolio.length;i++){ //console.log("i am here") var regind; var sreind; var sid = advisor_portfolio[i]; //console.log(advisor_portfolio[i]) if (sid.Reg_progress_ind == "R"){ regind = "<img src=\"/static/images/1red_star.png\" height =\"13\" width=\"13\" alt=\"R\">"; //console.log(regind); } else if(sid.Reg_progress_ind == "Y"){ regind = "<img src=\"/static/images/2yellow_star.png\" height =\"13\" width=\"13\" alt=\"Y\">"; //console.log(regind); } else … -
django -how to read uploaded csv file which one field contain '\n'
I encountered a problem when I try to read a uploaded csv file which one field contains '\n' character. e.g. I have a csv file, its content like this: 1. row 1: "one", "this is \nsample", 2. row 2: "two", "this is also \nsample". I can get the uploaded file in request.FILES successfully, but when I loop the file, the row will break down because '\n' character. My code is: file = request.FILES.get('filename', None) for line in file: if line: line = line.decode("utf-8") fields_set = list(csv.reader([line], skipinitialspace=True))[0] In first loop, the content of variable 'line' is: "one, this is". And in second loop, the variable'line' get the value "sample". but what I want is to get 'one, "this is \nsample"'. Any help are appreciate, thanks in advance. -
Using Slack Interactive Buttons with a custom Slack app
A little bit confused about how to use the interactive buttons with my current slack application. I have the app authorized and I have the slack token with these scopes:identify,bot,commands,incoming-webhook. Whenever I press one of the buttons, I get "Oh no, something went wrong. Please try that again." How is the POST message sent to my specified URL? I assumed the buttons worked similarly to slash commands, but the POST requests from the buttons are not being interpreted. I'm also confused about how I'm actually supposed to use Slack Token to make a response back to slack. At the moment this is how I'm responding to slash commands: def post(self, request, format=None): base = {"response_type": "in_channel","mrkdwn":True} base['text'] = "Testing" command = request.data["text"].strip() if request.data["text"] == "test": return Response(base) -
How Access angular passed parameters in django views
I was trying to post the data using angular $http.post method in django,i wanted to know how will i access that parameter value in my django views:- Here is my controller.js var nameSpace = angular.module("ajax", ['ngCookies']); nameSpace.controller("MyFormCtrl", ['$scope', '$http', '$cookies', function ($scope, $http, $cookies) { $http.defaults.headers.post['Content-Type'] = 'application/json'; // To send the csrf code. $http.defaults.headers.post['X-CSRFToken'] = $cookies.get('csrftoken'); // This function is called when the form is submitted. $scope.submit = function ($event) { // Prevent page reload. $event.preventDefault(); // Send the data. var in_data = jQuery.param({'content': $scope.card.content,'csrfmiddlewaretoken': $cookies.csrftoken}); $http.post('add_card/', in_data) .then(function(json) { // Reset the form in case of success. console.log(json.data); $scope.card = angular.copy({}); }); } }]); Here is what i am attempting to access those in my view function:- card.content =request.POST.get('content') where card is my model's object,But i am getting NameError: name 'content' is not defined,Please help me out! -
Best way to save and display logs for multiprocess web app Django
We have a Django application with multiprocessing. Each process have it own log. How to store it? In DB or in separated files? -
how to take image path from html form
i need take image path from html form using django app. i know in the images field save the paths of images and not the images in database i need to take some from that paths using html form. i use this test=request.POST.get('cars') but not work because in print in debug show me none how to take image path ? class MyModel(models.Model): user = models.ForeignKey(User, unique=True) images = models.ImageField(upload_to='upload') views.py @login_required(login_url="login/") def disaster(request): #Myform = MyModelForm(user=request.user) photos=MyModel.objects.filter(user=request.user) test=request.POST.get('cars') print test return render(request,'about.html',{'photos':photos}) html : <form action=""> <select name="cars"> {% for photo in photos %} <option value="{{ photo.upload.url }}">{{ photo.upload.name }}</option> {% endfor %} </select> -
Error "Page no found(404)" using Django-Social-Auth in Django project
I am using Django-social-auth to login on my application. I used official documentattion and this tutorial but when I want to login, django throw me an error. The error is this: Page not found(404) Request Method: GET Request URL: http://127.0.0.1:8000/login/google-oauth2/ Raised by: social_django.views.auth Backend not found And I don't know why and how to solve it... I think the problem is in the urls. First I install social auth app: $ pip install social-auth-app-django and then I configure everything. The configuration... setting.py TEMPLATE_CONTEXT_PROCESSORS = ( "django.contrib.auth.context_processors.auth", "django.core.context_processors.debug", "django.core.context_processors.i18n", "django.core.context_processors.media", "django.core.context_processors.static", "django.contrib.messages.context_processors.messages", "django.core.context_processors.request", "social_django.context_processors.backends", #<-- "social_django.context_processors.login_redirect", #<-- "athento_context_processors.addons_settings", ) AUTHENTICATION_BACKENDS = ( #'social.backends.linkedin.LinkedinOAuth2', #'athento_backends.AthentoLDAPBackend' 'social_core.backends.google.GoogleOAuth2', 'social_core.backends.google.GoogleOAuth', 'social_core.backends.github.GithubOAuth2', 'social_core.backends.twitter.TwitterOAuth', 'social_core.backends.facebook.FacebookOAuth2', 'django.contrib.auth.backends.ModelBackend', ) MIDDLEWARE_CLASSES = ( # 'pyinstrument.middleware.ProfilerMiddleware', 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'social_django.middleware.SocialAuthExceptionMiddleware', #<-- ) INSTALLED_APPS = ( ...... ...... 'social_django', ) # SETTING_SOCIAL_AUTH LOGIN_URL = 'login' LOGOUT_URL = 'logout' LOGIN_REDIRECT_URL = 'home' SOCIAL_AUTH_URL_NAMESPACE = 'social' # END_SETTING_SOCIAL_AUTH # SETTING_OAUTH2_KEY SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = '<my key>' SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = '<my key>' # END_SETTING_OAUTH2_KEY urls.py urlpatterns = patterns('', ...... ...... ...... url(r'^home/$', 'views.index', name='home'), url(r'^login/$', 'views.index', name='login'), ...... ...... url(r'^oauth/', include('social_django.urls', namespace='social')), ) views.py def index(request): import os domain = request.META.get('HTTP_HOST', 'domain.com').split('.')[0] context = {'user': request.user, 'request': request, 'CLOUD': CLOUD, 'SIGNUP': SIGN_UP_ENABLED} domain_image = domain … -
Django: KeyError 'user' - update to 1.10
i updated my Django version from 1.9 to 1.10. Now, I get this KeyError. I hadn't this error message before. I looked at the changes of django version, but find nothing helpful. Here the error message: --- Logging error --- Traceback (most recent call last): File "/usr/lib/python3.4/logging/__init__.py", line 978, in emit msg = self.format(record) File "/usr/lib/python3.4/logging/__init__.py", line 828, in format return fmt.format(record) File "/usr/lib/python3.4/logging/__init__.py", line 568, in format s = self.formatMessage(record) File "/usr/lib/python3.4/logging/__init__.py", line 537, in formatMessage return self._style.format(record) File "/usr/lib/python3.4/logging/__init__.py", line 381, in format return self._fmt % record.__dict__ KeyError: 'user' Here some parts of my settings.py: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', # own context_processor for admin request 'test_modul.context_processors.global_settings', ], }, }, ] So I have included django.contrib.auth.context_processors.auth. Maybe somebody have for me an idea. -
Django_db mark for django parametrized tests
I have been learning django for the past few weeks and I tried using the parametrizing fixtures and test functions and from what I understood I can simply run multiple tests at once. With the parametrized test I am trying to test functions, which are found in all models. I read the documentation, but sadly, as soon as I tried it I got the following error message Database access not allowed, use the "django_db" mark, or the "db" or "transactional_db" fixtures to enable it.. I did read about the error and possible fixes and what I found was to create an autouse fixture and put it in conftest.py: import pytest @pytest.fixture(autouse=True) def enable_db_access_for_all_tests(db): pass Sadly, this change made 0 difference and I received the same exact error after running the test. I did also try to use the django_db mark to grant the test access to the database, but that also did not seem to work. -
Django import/reformat JSON into Model
I like to periodically import json data into a Django. What's the best way to import the data below to a Django model. As far as I've seen is the best approach to use Django fixtures. Since my Model looks like this and I can't change the given JSON, what's the best way to import the data or restructure the JSON to use it as a fixture. Django Model class Item(models.Model): item_name = models.CharField(max_length=250) timestamp = models.DateTimeField() value01 = models.DecimalField(max_digits=7, decimal_places=2) value02 = models.DecimalField(max_digits=7, decimal_places=2) Data I like to store: Item1 | 2017-04-18 09:24:46 | 15.00 | 12.68 Item1 | 2017-04-18 09:25:44 | 14.92 | 12.42 Given JSON: [ { "id": 1, "timestamp": "2017-04-18 09:24:46", "details": { "id": 843, "color": "white" }, "item": { "id": 1691, "category": "1", "item_type": { "id": 14, "name": "Item1" } }, "itemdatavalues": [ { "id": 227, "value": "15.00" }, { "id": 228, "value": "12.68" } ] }, { "id": 2, "timestamp": "2017-04-18 09:25:44", "details": { "id": 843, "color": "white" }, "item": { "id": 161, "category": "1", "item_type": { "id": 14, "name": "Item1" } }, "itemdatavalues": [ { "id": 283, "value": "14.92" }, { "id": 284, "value": "12.42" } ] } ] -
using webcomponent imports with django
Running a django app that serves web components, I am wondering how I can make a {% static %} tag resolution on collectstatic. For Example having the following web component (that is a static file - the static tag does not work): <link rel="import" href="{% static "polymer/polymer.html" %}/> <link rel="import" href="{% static "myapp/other_component.html" %}/> <dom-module id="hello-element"> <template>Hello there</template> </dom-module> <script> Polymer({ is: "hello-element" }) </script> I would like the collectstatic command to resolve the static tag on execution. I cannot use just static paths, e.g. /static/polymer/polymer.html because I am using: STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.ManifestStaticFilesStorage' which appends a hash to any static file. On the other hand I would not like to serve the components as a template as it would impair the performance. How do I make collectstatic resolve the {% static %} attribute in static files on runtime? -
Django redirect user to app based on permission and group
Say i have a django project which have 4 apps 1 app is for logging in project urls: from django.conf.urls import url, include from django.contrib import admin from django.conf import settings urlpatterns = [ url(r'^', include('Login.urls')), url(r'^admin/', admin.site.urls), ] settings: LOGIN_REDIRECT_URL = '/' login app urls: from django.conf.urls import url from django.contrib.auth import views as auth_views urlpatterns = [ url(r'^login/$', auth_views.login, name='login'), url(r'^logout/$', auth_views.logout, {'next_page': '/'}, name='logout'), ] now say i have 3 apps based on user type i.e. Admin, Team Lead, Worker so i want to redirect user based on their type of employment. how can i achieve this ? any help is appreciated -
Ionic: A bit Strange CORS issue with the IOS emulator
This is the code. $http({ method: 'GET', url: imageUrl }); I'm using the Ionic framework. It works fine in web, andorid mobile and android emulator. But when I use the same in the IOS 9.3 emulator(4.1.1), I get the error XMLHttpRequest cannot load 'imageUrl'. Origin 'XXX' is not allowed by Access-Control-Allow-Origin. I suppose I can eliminate any possible errors in the backend, as it is working with the other UI frameworks. Also in the backend(Django framework) I've set CORS_ORIGIN_ALLOW_ALL and CORS_ALLOW_CREDENTIALS to True, added the IP address with port to CORS_ORIGIN_WHITELIST and the needed headers(including Access-Control-Allow-Origin) in CORS_ALLOW_HEADERS. So, Is there anything specific that needs to be done to make this error go away for the IOS emulator / platform ? -
3d distance calculations with GeoDjango
I am using python 2.7.12 django 1.10.6 postgreSQL 9.5.6 postGIS 2.2.2 First question I need to use GeoDjango to calculate distance between two points. When I checked the documentation https://docs.djangoproject.com/en/1.10/ref/contrib/gis/geoquerysets/#distance it says that GeoQuerySet.distance() is deprecated and instead use Distance() from django.contrib.gis.db.models.functions. The following code works OK: from django.contrib.gis.db.models.functions import Distance p1 = Instrument.objects.get(pk=151071000).coordinates p2 = Instrument.objects.filter(pk=151071008) for i in p2.annotate(distance=Distance('coordinates', p1)): print i.distance print i.distance.__class__ Output: 461.10913945 m <class 'django.contrib.gis.measure.Distance'> My model: class Instrument(models.Model): ... coordinates = gis_models.PointField(null=True, blank=True, dim=3) But I have only two points so when I try to use Distance() without annotate() it returns instance of class django.contrib.gis.db.models.functions.Distance() rathen than django.contrib.gis.measure.Distance(): p1 = Instrument.objects.get(pk=151071000).coordinates p2 = Instrument.objects.get(pk=151071008).coordinates print Distance(p1, p2) Output: Distance(Value(SRID=4326;POINT Z (-76.48623600000001 44.260223 0)), GeomValue(SRID=4326;POINT Z (-76.490923 44.262658 0))) How do I receive the same result as with using annotate()? Second question I have to calculate 3d distance that is taking into account depth/elevation. But when I try to do it I receive the same result as with 2d. Below I changed elevation to 200 in the first object: p1 = Instrument.objects.get(pk=151071000) p1.coordinates = 'SRID=4326;POINT Z (-76.48623600000001 44.260223 200)' p2 = Instrument.objects.filter(pk=151071008) for i in p2.annotate(distance=Distance('coordinates', p1.coordinates)): print i.distance Output: 461.10913945 m -
if condition in django template "{{ }}"
Before showing a text I have to evaluate it. Instead of {% if value %} text_true {% else %} text_false {% endif %} Are there anything like: {{ text_true if value else text_false }} -
Django template not re-rendering on succesful AJAX get request
I have written a very simple ajax code which makes a get request, and it expects django template values as response. So when I try to execute this ajax code, in chrome under network, I can see that the get request was succesful and in the preview section under network, I can see the template values that I had expected but the webpage remains same, doesn't get rendered again. My view: def test(request,id=1): return render(request,'test.html',{'num':id,'next':9}) My template and ajax code: <script src='https://code.jquery.com/jquery-3.2.1.min.js'></script> <p>{{num}}</p> <button onclick='test({{next}})'>Test</button> <script> function test(next){ $.ajax({ url:'/test/'+next, type: 'GET', success: function(){ console.log('done'); } }); } </script> Please check this sample image of my problem when I started on '/test/66' , made a click on the button, got the required response, still no change. -
take image path from select django form
i have a django app and i working with upload images user authentication and django select form. in the django select form i have some question about how to work this first i upload images correct before with other form. second i create a select django form list with self login user images. now i need take that selection image path to do some image processing from this form. image form i have create something but i am not sure if is correct but i am sure that is not where i need. here the code : models.py class MyModel(models.Model): user = models.ForeignKey(User, unique=True) upload = models.ImageField(upload_to='upload') views.py @login_required(login_url="login/") def myview(request): Myf = MyModelForm(user=request.user,data=request.POST) print myf return render(request,'home.html',{'Myf':Myf}) form.py class MyModelForm(ModelForm): def __init__(self, *args, **kwargs): if 'user' in kwargs: self.user = kwargs.pop('user') super(MyModelForm, self).__init__(*args, **kwargs) choices = [(obj.id, obj.upload.url) for obj in MyModel.objects.filter(user=self.user)] self.fields['upload'].widget = Select(choices=choices) class Meta: model = MyModel fields = ('upload',) html page : <form class="" action="" method="post" enctype="multipart/form-data"> {% csrf_token %} {{ Myform}} <input type="submit" name="" value="Submit"> </form> debug mode : [18/Apr/2017 16:03:36] "GET /favicon.ico HTTP/1.1" 404 2926 <tr><th><label for="id_upload">Upload:</label></th><td><ul class="errorlist"><li>This field is required.</li></ul><select id="id_upload" name="upload" required> <option value="1">/media/user_2/image1.jpg</option> <option value="3">/media/user_2/image2.jpg</option> <option value="4">/media/user_2/image3.jpg</option> <option value="5">/media/user_2/image4.jpg</option> <option …