Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Post Api using Rest Framework
So I was tring to create a POST Api for my project where on the html page, user enter his details and message and press the encrypt button, then an encrypted msg should be shown in the container given below and his details should be stored in DB. Here is the image of what the page is like. https://imgur.com/a/3hnAA But the problem is as you can see encrypted message is shown below but the post api is not working. All i want is to create an entry in DB and the user also stay on this page only. Here are my Django file. All the files can be found here. https://github.com/MukulLatiyan/Vigenere-Cipher models.py from __future__ import unicode_literals from django.db import models class User(models.Model): name = models.CharField(max_length=255) email = models.CharField(max_length=255) message = models.TextField(max_length=40000) enc_message = models.TextField(max_length=40000) created_on = models.DateTimeField(auto_now_add=True) views.py from __future__ import unicode_literals from models import User from forms import MainForm from django.shortcuts import render from serializers import UserSerializer from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from rest_framework.permissions import AllowAny def main_view(request): if request.method == "POST": form = MainForm(request.POST) if form.is_valid(): name = form.cleaned_data['name'] email = form.cleaned_data['email'] message = form.cleaned_data['message'] enc_message = form.cleaned_data['enc_message'] ## SAVING DATA … -
How would I debug CKAN using a breakpoint based debugger in Visual Studio Code?
I'm a fairly experienced developer just recently diving into the world of Python development via CKAN as an entrypoint. So far, I understand very simple configurations, like running a single python file, setting a breakpoint, and waiting for it to be hit. That much I can follow because it's obvious to me where the application starts up. With CKAN, I'm not quite sure where I'd even run the debugger from. However, when it comes to a more extensive system like CKAN (or perhaps others like Django), I haven't been able to quite figure out how all the pieces come together. Typically I'll start up a dev server using paster serve and it will run a webserver on port 5000. Using this knowledge as a baseline, what steps might I take to get to the point where I can place a breakpoint in an extension, start up CKAN, wait for the breakpoint to be hit, and then inspect the current values of variables and so on? FWIW, I'm running CKAN in production on Ubuntu 14.04 and in development on macOS 10.11 in a virtualenv. I feel like the problems I'm facing might be because the various components of CKAN, and python … -
Ubuntu Setting Environment Variables for Django
I have a Django project running on Ubuntu 16.04 with Nginx and Gunicorn. I am trying to set an environment variable in order to load a different settings file for production. I have tried the following to no prevail. In etc/environment I added my variable. The file looks like this, PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games" PRODUCTION="Production_Variable" The value of the variable is irrelevant. When I run printenv I can see that this variable is actually present! However my django project still does not "see" it. try: if 'PRODUCTION' in os.environ: from .prod import * except: pass I am a bit confused that printenv shows that the environment variable is present, yet Django cannot see it. Does anything look blatantly wrong with what I am attempting? -
app_template and project_template : custom variables
When starting projects or apps with custom app_template or project_template, is there a way to pass custom variable to the executable to use them in the -tpl files? For instance I'd like to start my projects directly with channels settings and I'd like to automatically the redis server. -
custom project_template : setting up default app_template for manage.py
I'm starting to make my own project_template and app_template. Is there a way to change the default project_template path so ./manage.py startapp would use a custom app_template path to make new apps? For instance by modifying the manage.py-tpl file. "No, there is no reasonnably simple way to achieve this" may also be a valid answer. -
I wanna mix color when I pull button
I wanna mix color when I pull button in drill down button. Now my web site has 2 drill down button like This website can be changed its background color&h1 letter & p letter by setting pull buttons. When I pulled first button and set color, background color & others were changed.But when I pulled second button and set color, nothing was changed.My ideal site is able to be changed colors were set by 2 buttons and mixed these colors.In this case,pink& green were selected, so my ideal background color is blown.I wanna mix colors of h1&p letters too. I really cannot understand why 2 colors are not mixed.I already registed background & h1 & p letters' color in models, so it is ok. models.py is from django.db import models # Create your models here. class Color(models.Model): name = models.CharField(max_length=255) background_color = models.CharField(max_length=255) h1_color = models.CharField(max_length=255) p_color = models.CharField(max_length=255) def __str__(self): return self.name forms.py is from django import forms from .models import Color class ColorForm(forms.Form): color = forms.ModelChoiceField( queryset=Color.objects.all(), empty_label=None, required=False, ) views.py is from django.shortcuts import render from .models import Color from .forms import ColorForm # Create your views here. def index(request): d = { 'colors': Color.objects.all(), 'form': ColorForm(), … -
static) files in django
I'm trying to get a file that's in my media directory to appear on an HTML template. I'm using the Tango with Django book as a tutorial. here is my settings.py MEDIA_DIR = os.path.join(BASE_DIR, 'media') MEDIA_ROOT = MEDIA_DIR MEDIA_URL = '/media/' Here is views.py def about(request): return render(request, 'rango/about.html', ) and my about.html <!DOCTYPE html> {%load staticfiles%} <html lang="en"> <head> <meta charset="UTF-8"> <title>About</title> </head> <body> <h1>This is the about page</h1> <img src="{{MEDIA_URL}} {{cat.jpg}}" alt="cats are funny"/> <div> <a href="/rango/"> Index </a> </div> </body> </html> I know I must be missing something very obvious, but can't figure it out for the life of me! -
How to setup python 3 from virtual environment as the default python for Django
I have a droplet from DigitalOcean. It runs Ubuntu 16.04. By default, it is using Python2. I have a website created with Django. I want to setup a virtual env and run python 3 in the virtual environment. The HTTP server in the droplet is NGINX. How can I let the droplet pick up the python 3 in the virtual environment as the python for my Django project? Thank! -
Django: Trying to get data form two views to show on one index page
I'm trying to display content from two different apps with two different views on my index page. I made a views.py for my project to handle the index page and I'm trying to connect the model instances in my two apps to it. I'm not getting any errors, however I can't get anything to show other than the stuff in my base.html. Here is the code along with the pictures to show what's happening vs. what I'm trying to do. Project views.py: from django.shortcuts import render from colorsets.models import ColorSet from adminpanel.models import Widget from django.utils import timezone from django.contrib.auth import authenticate,login,logout from django.http import HttpResponseRedirect, HttpResponse from django.core.urlresolvers import reverse,reverse_lazy def home(request, template='index.html'): context = { 'widget': ColorSet.objects.all(), 'color_set': Widget.objects.all(), } return render(request, template, context) Project urls.py: """colors URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.11/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL … -
HTML5 input not working with keyboad's 10 key
I am having an odd issue that I can't explain with one of the inputs of type text I have in one of my Django app's templates. I can enter in numbers on a mac using the number keys on the top, but when someone uses a keyboard that has a 10 key, and enters a number using that 10 key, the input doesn't register it at all ? A couple other things to note is that I am using Angular on the frontend of the app, and have inline javascript for quick validation, we had an issue with our Zip input truncating leading zeros because it was initially of type 'number'. Has anyone faced this issue before in the past ? HTML Input <input type="text" onkeydown="javascript: if ((event.which < 48 && event.which != 8) || event.which > 57) event.preventDefault();" placeholder="-" ng-model="homeState.search.zip" maxlength="5" oninput="javascript: if (this.value.length > this.maxLength) this.value = this.value.slice(0, this.maxLength);"/> I thought maybe the key codes were different when using the 10 key, but they are exactly the same. -
CSRF Token in Ajax - Post Api
So, I'm like digging stack overflow from 2 days but cant find solution to my exact problem. My problem is that I've made a POST API using django, which I'm calling on a button. But evertime time it gives csrf token error. Everytime the post request return 403. IDk where I'm going wrong. Please Help. I'm writing my code down below.Rest of the code can be found here. https://github.com/MukulLatiyan/Vigenere-Cipher API in views.py class UserList(APIView): permission_classes = (AllowAny,) def get(self, request, format=None): user = User.objects.all() user = UserSerializer(user, many=True) return Response(user.data) def post(self, request, format=None): serializer = User.objects.create() serializer = serializer(data=request.DATA) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) This is the API call I'm making in AJAX var token = $("meta[name='_csrf']").attr("content"); var data = '{"inputs":[{"data":{"name":{"email"::{"msg"::{"enc_msg"}}}]}' $("encrypt_button").on("click", function(e){ e.preventDefault(); $.ajax({ 'type': 'POST', 'url': '/users/', beforeSend: function(xhr) { xhr.setRequestHeader('X-CSRF-TOKEN', token); }, 'data': data, success: function (response) { console.log(response.outputs); }, error: function (xhr) { console.log(xhr); } }) }) This in my Urls.py urlpatterns = [ url('users/', views.UserList.as_view()), url('', main_view) ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) And this is my index.html {% load staticfiles %} <!DOCTYPE html> <html lang="en-Us"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <title>Vignere Cypher</title> </head> <body> <div class="container"> <h1>Vignere … -
Where do you deploy your Django application online?
I'm developing a web application with django. I used to use Openshift to publish/deploy my work. What do you think is the best platform? My only requisite is to have an usable and scalable free plan. Then when things comes bigger I will pay. -
Leaflet Map only opening one popup
I have a "Store Locator/Hot Spot Locator" on my Leaflet Map. It has a few places that I use django to populate the layer list. {% autoescape off %} {% for l in layer %} <a class = "title"> <div class="item"> <button onClick="choose({{l.id}},{{l.gpin_lat}},{{l.gpin_long}});">Find</button> <boring html> </div> </a> {% endfor %} {% endautoescape %} So basically I have some javascript that pans the leaflet map to a specific lat/long point. That is good. <script> function choose(id,lat1,long1){ var latlngPoint = new L.LatLng(lat1,long1); map.panTo(latlngPoint,20); maplayer.openPopup(latlngPoint); } </script> So, here's the weird part. The map is panning too (Issue with some zooming but I don't care at this point, and it is opening the popup. The issue is no matter what the lat/long is it is opening the popup of the first item in the list at that lat long. So let's say i have lat/long a,b with a popup of X and I have a lat,long c,d with a popup of Y. It is opening X at (c,d). Sorry in advance. I don't pretend to know javascript. -
Django agregation with parameters
My task is - i want for each object1 get latest object2 by its creation date. But firstly i want to apply some filter: Orm query: Object2.objects.filter(status='fail').annotate(max_date=Max('object1__object2__created')).filter(created=F('max_date') And its works fine if last created object2 having fail status - but if it have another status - i get no result for this object, because Max looks on all objects not just status='fail' and if latest object have another status - i dont get any result for this object1 When i look on sql query it generated i see that its don't filter objects in Max by status='fail' it get all related objects - is where a way to achieve that i want? Can i somehow pass query to Max? Sql: SELECT ...., MAX(T3."created") AS "max_date" FROM "object2" INNER JOIN "object1" ON ( "object2"."object1_id" = "object1"."id" ) LEFT OUTER JOIN "object2" T3 ON ( "object1"."id" = T3."repo_id" ) WHERE "object2"."status" = fail GROUP BY ... HAVING "object2"."created" = (MAX(T3."created")) Instead of LEFT OUTER JOIN "object2" T3 ON ( "object1"."id" = T3."repo_id" ) I want something like LEFT OUTER JOIN "object2" T3 ON ( "object1"."id" = T3."repo_id" and "object2"."status" = fail) How can i achieve this? -
TemplateDoesNotExist at /account/login/
I am a bit stumped trying to get auth to work. I have checked through my urls files and can't see anything there. No exceptions from views.py but keep getting TemplateDoesNot Exist Request Method: GET Request URL: http://127.0.0.1:8000/account/login/ Django Version: 1.8.6 Exception Type: TemplateDoesNotExist Exception Value: account/login.html Exception Location: /Users/me/book/venv/lib/python3.6/site-packages/django/template/loader.py in get_template, line 46 Python Executable: /Users/me/book/venv/bin/python Python Version: 3.6.2 Python Path: ['/Users/me/book/venv/bookmarks', '/Users/me/book/venv/lib/python36.zip', '/Users/me/book/venv/lib/python3.6', '/Users/me/book/venv/lib/python3.6/lib-dynload', '/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6', '/Users/me/book/venv/lib/python3.6/site-packages'] Server time: Fri, 1 Sep 2017 20:33:29 +0000 Traceback here: Environment: Request Method: GET Request URL: http://127.0.0.1:8000/account/login/ Django Version: 1.8.6 Python Version: 3.6.2 Installed Applications: ('django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles') Installed Middleware: ('django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware') Template Loader Error: Django tried loading these templates, in this order: Using loader django.template.loaders.filesystem.Loader: Using loader django.template.loaders.app_directories.Loader: /Users/me/book/venv/lib/python3.6/site-packages/django/contrib/admin/templates/account/login.html (File does not exist) /Users/me/book/venv/lib/python3.6/site-packages/django/contrib/auth/templates/account/login.html (File does not exist) Traceback: File "/Users/me/book/venv/lib/python3.6/site-packages/django/core/handlers/base.py" in get_response 132. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/me/book/venv/bookmarks/account/views.py" in user_login 22. return render(request, 'account/login.html', {'form': form}) File "/Users/me/book/venv/lib/python3.6/site-packages/django/shortcuts.py" in render 67. template_name, context, request=request, using=using) File "/Users/me/book/venv/lib/python3.6/site-packages/django/template/loader.py" in render_to_string 98. template = get_template(template_name, using=using) File "/Users/me/book/venv/lib/python3.6/site-packages/django/template/loader.py" in get_template 46. raise TemplateDoesNotExist(template_name) Exception Type: TemplateDoesNotExist at /account/login/ Exception Value: account/login.html -
How to render stored Javascript code in Django Models?
I am using django for research and have an expensive computing process that takes about 12 or 13 hours and generates javascript charts. I did the computing using the management command and stored the charts in the models as TextField. My question is how to display this javascript code on the template? I tried using {{ variable_name }} results in plain javascript text I also tried using <script type="javascript"> {{ data.word_graph }} </script> resulted in text with special characters. -
How to translate countries according to browser's language preference
RE: To circumvent the answer police I'm posting this as a question (see Translate country names to match browser language preference) I muddled the question. The template is a list of countries. There's no form involved. Remove steps 3 and 4 above. Put {% load i18n %} at the top of your template (e.g. in country_list.html) Change {{ country.name }} in the html loop to {% trans country.name %}, Works for Portuguese (e.g. Azerbaijan comes out Azerbaijão) Background for those who have aren't familiar with Django: my Model is for a simple table of countries in Postgres. The list view looks like: class CountryList(PageLinksMixin, ListView): paginate_by = 300 model = Tag The html now looks like: {% for country in country_list %} ... {% trans tag.name %} ... {% endfor %} -
Django filters not applying when going to next page
I am using Django filters and when I apply the filters they originally they work but when I go to the next page of results they reset. I have looked at this post django-filter use paginations but they seem to be doing the same things that I am. What am I doing wrong? Url url(r'^relations/$', views.annotation_views.relations, name="relations") returns a url like this when the filters are applied: /relations/?createdBy=&occursIn=&createdAfter=&createdBefore=&terminal_nodes=&project= Filters.py class RelationSetFilter(django_filters.FilterSet): occursIn = django_filters.CharFilter('occursIn__uri', method='filter_occursIn') createdBefore = django_filters.DateTimeFilter('created', lookup_expr='lt') createdAfter = django_filters.DateTimeFilter('created', lookup_expr='gt') terminal_nodes = django_filters.CharFilter('terminal_nodes__uri') def filter_occursIn(self, queryset, name, value): if not value: return queryset return queryset.filter(Q(occursIn__uri=value) | Q(occursIn__part_of__uri=value) | Q(occursIn__part_of__part_of__uri=value)) class Meta: model = RelationSet fields = ['createdBy', 'project', 'occursIn', 'terminal_nodes'] View def relations(request): from annotations.filters import RelationSetFilter qs = RelationSet.objects.all() filtered = RelationSetFilter(request.GET, queryset=qs) qs = filtered.qs for r in qs: print r.__dict__ paginator = Paginator(qs, 40) page = request.GET.get('page') try: relations = paginator.page(page) except PageNotAnInteger: # If page is not an integer, deliver first page. relations = paginator.page(1) except EmptyPage: # If page is out of range (e.g. 9999), deliver last page of results. relations = paginator.page(paginator.num_pages) context = { 'paginator': paginator, 'relations': relations, 'params': request.GET.urlencode(), 'filter': filtered, } return render(request, 'annotations/relations.html', context) -
How to use external django API data in html dropdown
I have an API which gives me json data. I would like to get some values out of that json and list as a drop down on my HTML. Do I need to create a form for that. For instance, I have a URL, http://netbox.com/api/deviceroles which gives a json file and I want to extract names out of it. deviceroles will consist of all the values of names. views.py import json, urlib def home(request): if request.method == 'GET' url = "http://netbox.com/deviceroles" response = urllib.urlopen(url) data = json.loads(response.read()) for i in range (0, len (data['results'])): deviceroles = data['results'][i]['name'] return render(request,"base.html") base.html <div class="em-c-field"> <label for="file" class="em-c-field__label">Device Role</label> <div class="em-c-field__body"> <select class="em-c-select em-c-select" id="file" placeholder="Placeholder"> <optgroup> <option value="" disabled="disabled" selected="selected">please select a device role</option> </optgroup> </select> </div> -
django post request to uploadcare success but file not uploaded (s3)
I am currently using django, instead of using the pyuploadcare I am writing a simple script to post the file with uuid using backend to push the file to s3 bucket Somehow I do get a success response back and I do see the pattern is created in s3 but then the file is not saved though. Can someone please give me a hand? this is what I have import requests headers = { 'Authorization': 'Uploadcare.Simple KEY:KEY' } payload = { 'pattern': 'uploadcare/', 'source': '03ccf9ab-f266-43fb-973d-a6529c55c2ae', // this exists in uploadcare 'target': 'bucket name', 'make_public': True } response = requests.post('https://api.uploadcare.com/files/', payload, headers=headers).json() print(response) # returns {u'type': u'url', u'result': u's3://bucket name/uploadcare/'} Thanks in advance for any help and advice. -
Django custom template tag is not being executed
I have a custom template tag that looks like this: {% extends 'forms/base_template.html' %} {% load mytags %} {% mytag user 'hello' as greeting %} {% block additional_info %} {{ greeting }} {% endblock %} My tags are something like this: from django import template register = template.Library() @register.assignment_tag(takes_context=False) def mytag(user, what_to_say): return "{what_to_say} {user}".format( what_to_say=what_to_say, user=user.name ) But the code is never executed and the greeting variable is empty. Any ideas what may be going on? -
How to specify which virtualenv to use in my django project?
I need help to understand how I can: 1) Choose which virtualenv my django project should use? As I understood maybe I'm wrong! when I activate the virtualenv that one my project will be using. But what about if I'm running on 1 server 2 different projects and each one should use it's own virtualenv? I'm looking for your help :) -
(Django, Satchmo) Developing products/cart line items with personalized fields/properties
I'm looking into Python/Django to evaluate suitable e-commerce solution. For now Satchmo package seems to deliver solution to satfy most of my needs with Subscription product type. However, I still have home requirements to meet and I ended wondering that is Satchmo or some other cart/commerce package suitable for personalized products? I need the user to fill in some "personal details" regarding Subscription since Subscription products/orders can be assigned to other users and/or to non-user. Most natural way would be to enable users to add these details after product has been added to cart. Line items should therefore have a user reference field or multiple fields in case of a non-user: email, phone,name,dob. -
Why gunicorn cannot find static files?
Running Django dev server has no problem: 'python manage.py runserver 9000' But if use gunicorn, it complains: 'http://innovindex.com/pubmed/static/js/jquery-3.2.1.min.js ' Why gunicorn cannot find a local jquery but Django can? The settings are: settings.py (seems not related): STATIC_URL = '/pubmed/static/' in '/etc/nginx/sites-enabled/django' location /static { alias /home/django/innovindex/pubmed/static/; } And my app looks like this: /home/django/innovindex is where the 'manage.py' sits. THANK YOU SO MUCH !!! -
Django Paginator: where does paginator modify SQL query to
I'm trying to hook up to django pagination system and got a low-level question. I've been digging through the code of Manager, Queryset and Paginator, but I can't find the place, where Paginator makes SQLCompiler set limit and offset on SQL query, forcing it to return only a part of queryset. Can you find that place? Cause it's not in the code of Paginator itself. Here's an example of SQL, generated by paginator: >>> from django.db import connection >>> >>> paginator = Paginator(Myobject.objects.filter(foreign_key='URS0000416056'), 1) >>> for myobject in paginator.page(1): >>> print myobject Myobject object >>> >>> print connection.queries [{u'time': u'0.903', u'sql': u'SELECT COUNT(*) AS "__count" FROM "xref" WHERE "xref"."upi" = \'URS0000416056\''}, {u'time': u'0.144', u'sql': u'SELECT "xref"."id", "xref"."dbid", "xref"."ac", "xref"."created", "xref"."last", "xref"."upi", "xref"."version_i", "xref"."deleted", "xref"."timestamp", "xref"."userstamp", "xref"."version", "xref"."taxid" FROM "xref" WHERE "xref"."upi" = \'URS0000416056\' LIMIT 1 OFFSET 1'}]