Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to keep form data when post fails and redirect with an error messages in Django?
I have been trying to look around but most answers are outdated. I have simple form and I am using python/django in my backend. index.html <form action="/add_blog" method="post"> <label for="title">Title</label> <input type="text" name="title" value=""> <label for="blog">Blog</label> <input type="text" name="blog" value=""> </form> There are more field there that when the form gets submitted and fails my backend validation, it will redirect back to 'index.html' and display some error messages. The question is, how can I preserve inputs so that when the post fails validation, the user won't lose their inputs and gives them time to edit their mistake. I have tried doing this: <form action="/add_blog" method="post"> <label for="title">Title</label> <input type="text" name="title" value="{{title}}"> <label for="blog">Blog</label> <input type="text" name="blog" value="{{blog}}"> </form> but it I need to pass a context on a redirect somehow. Is there a better and clean way to do this? Thanks a lot! -
How to ignore or handle django-hijack from the command line?
I'm writing some unit tests for an existing django project that has had no unit tests to date. When I run the tests from the command line using ./manage.py test I get Traceback (most recent call last): File "./manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line utility.execute() File "/usr/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 341, in execute django.setup() File "/usr/local/lib/python2.7/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/local/lib/python2.7/site-packages/django/apps/registry.py", line 85, in populate app_config = AppConfig.create(entry) File "/usr/local/lib/python2.7/site-packages/django/apps/config.py", line 90, in create module = import_module(entry) File "/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) ImportError: No module named hijack Now hijack is actually installed as I can use it from the browser when I run the server using ./manage.py runserver So ... how I can disable the reference for hijack when running tests or how can I enable hijack to be available under the command line when running tests? (can someone create and add the tag django-hijack) -
Does searching by id depends on number of columns in postgres?
I have the following query: MyModel.objects.filter(id__in=ids). I noticed that increasing number of columns in table decreases speed of the above query. Why is that? -
How I access a table before select id of another table in Django
I'm new to Django and I was following the steps in the Django Projects Tutorial and adapting to my goal: creating a questionnaire but I am having a problem accessing the data from another table after selecting the test id. Here are the files (sorry for my English). models.p from django.db import models from django.utils.encoding import python_2_unicode_compatible class Prova(models.Model): idProva = models.CharField(max_length=5,primary_key=True,null=False) tipoProva = models.CharField(max_length=5,null=False) anoProva = models.CharField(max_length=4,null=False) def __str__(self): return self.idProva class Usuario(models.Model): matriculaUsuario = models.CharField(max_length=12,primary_key=True,null=False) nomeUsuario = models.CharField(max_length=200,null=False) tipoUsuario = models.CharField(max_length=1,null=False) emailUsuario = models.EmailField(null=False) senhaUsuario = models.CharField(max_length=20,null=False) def __str__(self): return self.matriculaUsuario class Questao(models.Model): idQuestao = models.CharField(max_length=7,primary_key=True,null=False) idProva = models.ForeignKey(Prova) areaQuestao = models.CharField(max_length=50,null=False) tipoQuestao = models.CharField(max_length=1,null=False) textoQuestao = models.CharField(max_length=500,blank=True,null=True) imagemQuestao = models.ImageField(null=True,blank=True) perguntaQuestao = models.CharField(max_length=200,blank=True,null=True) statusQuestao = models.CharField(max_length=1,null=False) def __str__(self): return self.idQuestao class Opcao(models.Model): idOpcao = models.CharField(max_length=8,primary_key=True,null=False) idQuestao = models.ForeignKey(Questao) aOpcao = models.CharField(max_length=200,null=False) bOpcao = models.CharField(max_length=200,null=False) cOpcao = models.CharField(max_length=200,null=False) dOpcao = models.CharField(max_length=200,null=False) eOpcao = models.CharField(max_length=200,null=False) escolhidaOpcao = models.CharField(max_length=200,null=True,blank=True) def __str__(self): return self.idOpcao class Historico(models.Model): idHistorico = models.CharField(max_length=10,primary_key=True,null=False) idProva = models.ForeignKey(Prova,null=False) matriculaUsuario = models.ForeignKey(Usuario,null=False) def __str__(self): return self.idHistorico class Resposta(models.Model): idResposta = models.CharField(max_length=9,primary_key=True,null=False) idQuestao = models.ForeignKey(Questao) matriculaUsuario = models.ForeignKey(Usuario) tipoResposta = models.CharField(max_length=1,null=False) certaResposta = models.CharField(max_length=1) textoResposta = models.CharField(max_length=1000) def __str__(self): return self.idResposta index.html <link rel="stylesheet" href="{% static 'polls/js/script.js' %}"> <link … -
How to receive RabbitMQ messages in a Django app? (Celery?)
We receive a RabbitMQ (or maybe Redis) message generated by an event external to our server. How to make our Django app to be notified on such event (and execute some our code)? Can it be done with Celery? -
d3 Bar chart with a tool tip is not working
I've been working with a D3 svg chart with built in tool tips (using the d3-tip library). The original code can be seen here: http://bl.ocks.org/Caged/6476579 I am using Django as back end and I am trying to populate log count as per year from datetime. I was successfully able to populate the axis and labels of the graph except the bars. Here is my html template called graph.html: <!DOCTYPE html> <meta charset="utf-8"> <style> body { font: 10px sans-serif; } .axis path, .axis line { fill: none; stroke: #000; shape-rendering: crispEdges; } .bar { fill: orange; } .bar:hover { fill: orangered ; } .x.axis path { display: none; } .d3-tip { line-height: 1; font-weight: bold; padding: 12px; background: rgba(0, 0, 0, 0.8); color: #fff; border-radius: 2px; } /* Creates a small triangle extender for the tooltip */ .d3-tip:after { box-sizing: border-box; display: inline; font-size: 10px; width: 100%; line-height: 1; color: rgba(0, 0, 0, 0.8); content: "\25BC"; position: absolute; text-align: center; } /* Style northward tooltips differently */ .d3-tip.n:after { margin: -1px 0 0 0; top: 100%; left: 0; } </style> <body> <script src="http://d3js.org/d3.v3.js"></script> <script src="http://labratrevenge.com/d3-tip/javascripts/d3.tip.v0.6.3.js"></script> <script> var margin = {top: 40, right: 20, bottom: 30, left: 40}, width = 960 - … -
Static site generator which updates in realtime
I’m trying to find a static site generator which is capable of updating static pages as changes are made to a django database. Would anyone known of an open source site generator which does this? -
TemplateSyntaxError django link
I'm using django 1.11 and python 3. I but a link in the page when i click it i get this error. any idea? -
django-ckeditor formatting not in html post
I have an issue similar to this previous question : Django-ckeditor not displaying correctly in html except that my settings seem to be ok but still not displaying in the html page. What am I missing? settings.py INSTALLED_APPS = [ 'ckeditor', 'ckeditor_uploader', ] CKEDITOR_CONFIGS = { 'awesome_ckeditor': { 'toolbar': 'full', }, } CKEDITOR_IMAGE_BACKEND = "pillow" and in the html page rendering the edited post I have: post_detail.html <div class="post-content">{{post.text|safe|linebreaksbr}}</div> Everything works fine on the admin side: yet it is not displayed on the page: -
Django foreign key backward relation does not work
I have a class B that contains a ForeignKey relation to class A. When I instantiate B I can access field 'a' but the reverse relation (which should be created automatically) raises an error. Concretely, I have the following class definitions: from django.db.models import Model, CharField, DateField, ForeignKey from django.urls import reverse class Patient(Model): GENDER = ( ('M', 'Male'), ('F', 'Female'), ('U', 'Unknown'), ) last_name = CharField(max_length=128, null=False) first_name = CharField(max_length=128, null=False, default='') gender = CharField(max_length=1, choices=GENDER, null=False) dob = DateField(null=False) def get_absolute_url(self): return reverse('patient_detail', args=[str(self.id)]) def __str__(self): return '{}, {} ({}, {})'.format(self.last_name, self.first_name, self.gender, self.dob) class AttributeSet(Model): name = CharField(max_length=128, null=False) description = CharField(max_length=256, blank=True, default='') def get_absolute_url(self): return reverse('attribute_set_detail', args=[str(self.id)]) def __str__(self): return self.name class AttributeSetInstance(Model): patient = ForeignKey('Patient', null=False) # Automatic 'attribute_set_instance_set' backward relation? attribute_set = ForeignKey('AttributeSet', null=False) def get_absolute_url(self): return reverse('attribute_set_instance_detail', args=[str(self.id)]) def __str__(self): return self.attribute_set.name When I try to create a new AttributeSetInstance with a Patient and AttributeSet argument I can access the patient and attribute_set fields, but not vice versa. Like so: Python 2.7.13 (v2.7.13:a06454b1afa1, Dec 17 2016, 12:39:47) [GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) >>> from app.models import Patient, … -
Django how to display img in template by setting MEDIA_ROOT
here is my settings MEDIA_ROOT = 'upload/' MEDIA_URL = '/upload/' where the path of upload folder is PROJECT_ROOT/myapp/upload. I successfully upload a file a.jpg to that folder, but in the render page it shows that /upload/a.jpg not found I'm confused about the media root setting. I think it's similar to STATIC_URL, my static url setting is like this: STATIC_URL = '/static/ and the path of static folder is PROJECT_ROOT/myapp/static and files like /static/a.css can ben rendered successful in web pages. -
ValueError on migrate Django Database
Whenever I want to migrate my Django Database I get the error message above. ValueError: invalid literal for int() with base 10: 'NA' However, my models are empty. When I check them with Model.objects.all() I get . And when I look at my models at Django Admin, they are empty as well. So how is it possible that there is any "NA" where there shouldn't be one? And how can I repair my database? Thanks for any help! -
Using Highchart with javascript
I used Highchart with Django Here is my value of temperature of a javascript object . [42, 42, 42, 42, 42, 42, 42, 42, 25.9, 26, 26.1] Here is my div in html: <div id="container2" style="width:100%; height:400px;"></div> chart.js $(document).ready(function(){ var endpoint = '/api/chart/data'; var temperature = []; var humidity = []; var uv = []; var light = []; var rainfall = []; var labels = []; $.ajax({ method: "GET", url: endpoint, success: function(data){ labels = data.labels; temperature = data.temperature; console.log(temperature); setChart(temperature); }, error: function(error_data){ console.log("error"); console.log(error_data); } }); $(function setChart(temperature){ console.log(temperature); Highcharts.setOptions({ title: { text: '過去24小時氣溫變化圖' }, chart: { backgroundColor: { linearGradient: [0, 0, 500, 500], stops: [ [0, 'rgb(255, 255, 255)'], [1, 'rgb(240, 240, 255)'] ] }, borderWidth: 2, plotBackgroundColor: 'rgba(255, 255, 255, .9)', plotShadow: true, plotBorderWidth: 1 } }); var chart2 = new Highcharts.Chart({ chart: { renderTo: 'container2', type: 'column' }, xAxis: { type: 'datetime' }, series: [{ data: temperature, #data: [8,7,5,6,4,2,3,1], pointStart: Date.UTC(2010, 0, 1), pointInterval: 3600 * 1000 // one hour }] }); }); }); The chart can be printed when uncommented the data in series.(#data: [8,7,5,6,4,2,3,1], But when it replaced by data: temperature, Then the some error comes from the following codes: setChart(temperature); Uncaught … -
use unique id in django model custom save
I am trying to create unique slugs from persons names, which will have obvious duplicates. My idea is to add the id to the slug as a unique identifier. The problem is that the unique id is not generated until the save completes. This is what I tried: def save(self, *args, **kwargs): if getattr(self, 'name', True): if not self.pk: matching_slugs = Entity.objects.filter(slug=slugify(self.name)) print matching_slugs if len(matching_slugs) > 0: self.slug=slugify(self.name+' temp') elif len(matching_slugs) == 0: self.slug=slugify(self.name) super(Entity, self).save(*args, **kwargs) self.slug=slugify(self.name+' '+str(self.id)) self.save() I get the error: maximum recursion depth exceeded in cmp I'm thinking this is not the best way to do this. How can I make names unique on save? -
Would installing LAMP fix Django/MySQL config issues?
Excuse me for the very broad question, but I seem to be going around in circles. I'm looking to build/develop a "web" app, using a MySQL database and host it on my RPi. In trying to do so, I've learnt that I need a webserver (apache2 seems to be the one these days) and that I needed to create an "app" to interface between them. Initially, I was using Python and Qt to try and build an app to be the interface, but found out that things weren't simple and I used to use Python/MySQL connectors etc. After a few weeks, I got things connected and then thought about the building of it. It became apparent that options like Flask & Django would be better suited for the task due to the frameworks. I found the DjangoGurls tutorial simple to follow when I read through it, so decided to give it a go, and just had to work out to substitute their PythonAnywhere.com deployment example, with my own server..........stuck. I've got things working on my laptop/development environment, but the server side of things isn't behaving. I know it's to do with the MySQL config/settings/permissions/path but I can't pinpoint it. There … -
Develop a mobile application based on an existing Django website/app
We have a website written in Django, that has been running for a few years. Now we would like to develop a mobile application for Android and iOS, using as much as possible from the Django-site. E.g. classes from models, like users and relevant functions, other data, etc What would be the best/easiest way to approach this issue. We have been looking at several other questions like this, but all seem to be a few years old Is there any options to using e.g. Django REST API? We are just a group of students, and any help/pointers on where to start would be much appreciated! -
Creating a queryset that subtracts 2 decimalfields
debts = Debt.objects.filter(debt_closed=False) for debt in debts: if debt.product.product_price - debt.product_paid <= 0: debt.debt_closed = True debt.save() debt.product.product_price and debt.product_paid are decimals. I need to subtract these two values in order to verify that the debt has been paid, so i can set mark boolean debt_closed true. The problem is, I will have to get every object, even the debts that are not paid yet. Is there any way to create a queryset that matches this condition? -
Django how to make flexible generic views
How do you make flexible generic views? At the moment I have two models one for apples and one for pears, and a single template I want to use. class AppleIndexView(generic.list): template_name = 'fruit/index.html' context_object_name = 'apple_list' def get_queryset(self): return Apple.objects.values() class PearIndexView(generic.list): template_name = 'fruit/index.html' context_object_name = 'pear_list' def get_queryset(self): return Pear.objects.values() Is there a way of being more DRY? There should be a better way. Thank you for your time -
Django How to get user (authenticated) ID in order to save data submitted by an anonymous user?
I am trying to let an anonymous user submit data through a modelform which is on a user's profile page and have that data saved (once submitted) to the user whose profile it was on. The approach I was thinking was to take in a 'pk' parameter to my view function (from my url pattern) and somehow correlate it to the user id of the page they are on and save it. Is there a way to get the user id of the profile page the anonymous user is submitting the form on? Or is there a better approach to doing this altogether? My model uses a foreign key to the authenticated User. I have one model which is a model for ideas (called Ideas) and they all belong to one user. And as new profiles get created, each user will have their own set of ideas and so on. Any help is greatly appreciated! -
Converting python2 library to python3
I have installed django-socketio using pip in my windows machine. Later I realized it has written in python2. I removed the package using the command pip uninstall django-socketio Then I downloaded the source code from here and refactored for python3 and installed it using the command python setup.py install but my example code still referring the python2 version code from somewhere. I haven't create any virtual environment. Any suggestions about what I have done wrong. Here is a part of my stacktrace.. ... File "<frozen importlib._bootstrap_external>", line 759, in source_to_code File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed File "../..\django_socketio\management\commands\runserver_socketio.py", line 57 print "SocketIOServer running on %s:%s" % bind ^ SyntaxError: Missing parentheses in call to 'print' If there is a way to find django-websocktio for python3 or good suggestion will be much helpful. Thank you. -
After switching from Django's default Users model to an AbstractUser model, Admin is looking for a Users_groups table
It became apparent the default User model wasn't going to work for me, nor extending it, so decided to make an AbstractUser model to use an existing table. Pretty much have everything working, except when I go to edit a user in Django Admin, I am getting an error: ProgrammingError at /adminauthentication/user/100826/change/ (1146, "Table 'test_db.Users_groups' doesn't exist") Not sure why it is trying to find this table as I haven't specified it, don't recall in the documentation needing to specify it, and thought AbstractUser would use other default tables that created with the initial migrate (e.g. auth_group or something). Not quite sure how to resolve, but I am looking into it. # ./admin.py from django.contrib import admin from django.contrib.auth.admin import UserAdmin from .models import User admin.site.register(User, UserAdmin) # ./models.py from django.db import models from django.contrib.auth.models import AbstractUser # Create your models here. # Extend the User model class User(AbstractUser): id = models.AutoField(primary_key=True) username = models.CharField(max_length=255, blank=False, null=False, unique=True) first_name = models.CharField(max_length=255, blank=True, null=True) last_name = models.CharField(max_length=255, blank=True, null=True) email = models.CharField(max_length=255, blank=True, null=True) phone = models.CharField(max_length=255, blank=True, null=True) password = models.CharField(max_length=255, blank=True, null=True) ip_whitelist_1 = models.CharField(max_length=32, blank=True, null=True) ip_whitelist_2 = models.CharField(max_length=32, blank=True, null=True) ip_whitelist_3 = models.CharField(max_length=32, blank=True, null=True) last_login = … -
Have Django traceback pinpoint where error occurred?
I have two questions about Django tracebacks. First, if I have a traceback like the following, I can see that the error is occurring in the 'review_new_profile' view as shown in the second traceback error below. Is it possible to tell Django to also display the line number in that view where the error occurred? /srv/http/example.com/venvs/725be8a8537aeef8021231ba68de3184bbd547b1/local/lib/python2.7/site-packages/django/core/handlers/base.py in get_response 1. response = wrapped_callback(request, *callback_args, **callback_kwargs) /srv/http/example.com/repo/profile/views.py in review_new_profile 1. user = User.objects.get(id=request.session['uid']) /srv/http/example.com/venvs/725be8a8537aeef8021231ba68de3184bbd547b1/local/lib/python2.7/site-packages/django/contrib/sessions/backends/base.py in __getitem__ 1. return self._session[key] What I'd like to see is something like the following where '540' is the line number in the views.py: /srv/http/example.com/repo/profile/views.py in review_new_profile (540) 1. user = User.objects.get(id=request.session['uid']) Second, am I correct in in thinking that the error actually occurred at the bottom-most line? So an interpretation of this trace is that Django was trying to generate a response to a request but when it tried to get a user instance for a given uid, it couldn't find the uid in the session? In other words, the error actually occurred on the last line in the traceback, where Django was trying to get the uid (key) from the session? -
Get random point from django PolygonField
TL,DR; I want to get a random point from a polygon (potentially) using ST_GeneratePoints. Background I'm making a GeoDjango webservice and have a collection of UK Postcodes with respective boundaries like so: from django.db import models as dj_models from django.contrib.gis.db import models as gis_models class Postcode(gis_models.Model): pretty_postcode = dj_models.CharField( max_length=8 ) coords = gis_models.PolygonField( default='POLYGON EMPTY' ) I've found a delightful little PostGis function ST_GeneratePoints, it can find me random points in my coords region. Your Challenge Your mission if you so choose it, is to show how to use this function from within my python django app (or suggest a better way). Ideally ending up with a function like so: from django.contrib.gis import geos # ... other imports ... class Postcode(gis_models.Model): # ... fields ... def get_random_point(self): rand_point = # code that executes ST_GeneratePoints # and returns a geos.Point instance return rand_point -
getting null when using Where clause in python sql
I have a table userToken with three columns: piEmail , piCode, piToken This is how I created this table: class UserToken(models.Model): piEmail = models.CharField(max_length=128) piCode = models.CharField(max_length=128) piToken = models.CharField(max_length=128, unique=True, default=uuid4) piToken is autoFill, I do not insert this value. Now I am inserting value in this table and in the next line trying to fetch the token value for the random value which I inserted in table: random_number = User.objects.make_random_password(length=10, allowed_chars='123456789abcdefghijklmno') userToken_instance = UserToken.objects.create(piEmail='abc@abc.com', piCode=random_number) cursor = connection.cursor() cursor.execute("SELECT piToken FROM app_usertoken where piCode = %s", (random_number,)) row = cursor.fetchall() But it is returning null , when I check in the table, value is there. -
NoReverseMatch at / having difficulties passing datasource to form action method
NoReverseMatch at /providers/121/update/ Reverse for 'provider_update' with arguments '(None,)' not found. 1 pattern(s) tried: ['providers/(?P\d+)/update/'] I know why the NoReverseMatch error is thrown, because the url cannot find parameters being identified. However, I don't understand why my parameters are not being passed to the right view. When I pass a var holding the parameters ID or PK it recognizes it as None, for some reason. I have looked at similiar questions, but they aren't having issues passing the data to the form action. Any help is appreciated!! Thanks partial_provider_update.html <form method="post" action="{% url 'provider_update' form.instance.id %}" class="js-provider-update-form"> {% csrf_token %} <div class="modal-header"> <h4 class="modal-title">Update Provider</h4> </div> <div class="modal-body"> {% include 'providers/includes/partial_provider_form.html' %} </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> <button type="submit" class="btn btn-primary">Update provider</button> </div> </form> partial_provider_list.html {% for provider in object_list %} <tr> <td>{{ provider.id }}</td> <td>{{ provider.name }}</td> <td>{{ provider.organization }}</td> <td>{{ provider.emr }}</td> <td>{{ provider.date|date:"Y-m-d" }}</td> <td style="width: 100px; vertical-align: center; padding-top: 9px"> <button type="button" style="height: 25px; font-size: 16px;width: 50px; padding: 0px" class="btn btn-warning btn-sm js-update-provider" data-url="{% url 'provider_update' provider.id %}"> Edit </button> </td> {% empty %} <tr> <td colspan="5" class="text-center bg-warning">No Providers</td> </tr> {% endfor %} urls.py from django.conf.urls import url, include from django.views.generic import …