Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
heroku django server error
Trying to deploy django project on heroku: https://crmtestnewone.herokuapp.com/crm/ Do all as this instruction said but getting error (Server Error (500)) https://github.com/DjangoGirls/tutorial-extensions/blob/master/heroku/README.md 2016-10-06T14:01:38.045036+00:00 heroku[router]: at=info method=GET path="/crm/" host=crmtestnewone.herokuapp.com request_id=4981504b-0314-48ee-8a1b-ef7c51062b8f fwd="95.108.174.232" dyno=web.1 connect=1ms service=53ms status=500 bytes=253 I only can enter /admin page 2016-10-06T14:03:37.432783+00:00 heroku[router]: at=info method=GET path="/admin/" host=crmtestnewone.herokuapp.com request_id=854e9324-a660-4a4e-ac19-8a9e693331c2 fwd="95.108.174.232" dyno=web.1 connect=0ms service=85ms status=200 bytes=4891 2016-10-06T14:03:37.596058+00:00 heroku[router]: at=info method=GET path="/static/admin/css/dashboard.css" host=crmtestnewone.herokuapp.com request_id=65fcb7df-bbe8-4731-aabc-24c1886c7300 fwd="95.108.174.232" dyno=web.1 connect=0ms service=2ms status=404 bytes=304 2016-10-06T14:03:37.597996+00:00 heroku[router]: at=info method=GET path="/static/admin/css/base.css" host=crmtestnewone.herokuapp.com request_id=2ed877bd-c9f7-4b3d-b613-c479d75d1ef1 fwd="95.108.174.232" dyno=web.1 connect=0ms service=3ms status=404 bytes=299 Can you give any advice to me? Why admin page working (i can create objects in my models), but look like pure html without any style and my other pages dont work at all? -
How to Login, Logout and User Registration through in build Authentication method?
view.py from django.contrib.auth import authenticate, login, logout from django.contrib.auth.decorators import login_required from django.contrib import messages # Create your views here. def signin(request): if request.method=='POST': username=request.POST['username'] password=request.POST['password'] user=authenticate(username=username,password=password) if user !=None: login(request,user) else: return HttpResponseRedirect('signin') else: messages.add_message(request, messages.ERROR, "Incorrect user or password") return render(request,'customer/login.html') def signout(request): logout(request) @login_required(login_url='customer/login.html') def createcustomer(request): if request.method == 'POST': form = CustomerForm(request.POST) if form.is_valid(): customer_save=Customer.objects.create( fname=form.cleaned_data['fname'], lname = form.cleaned_data['lname'], email= form.cleaned_data['email'], address= form.cleaned_data['address'], city=form.cleaned_data['city'], state=form.cleaned_data['state'], zip=form.cleaned_data['zip'], uname=form.cleaned_data['uname'], password=form.cleaned_data['password'], age=form.cleaned_data['age'], mobile=form.cleaned_data['mobile'], phone=form.cleaned_data['phone'], ) customer_save.save() return HttpResponseRedirect('thanks') else: form = CustomerForm() return render(request, 'customer/createcustomer.html', {'form': form}) login.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Edit Custmer Tasks</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> <title>Login</title> </head> <body> <div class="container-fluid" style="background-color: #f2f2f2;border:solid;" > <div class="col-md-4"></div> <div class="col-md-4"> <form class="login-page" method="post" action=""> <div class="input-group margin-bottom-20"> <span class="input-group-addon"> <i class="fa fa-user"></i> </span> <input type="text" name="username" class="form-control" placeholder="Username/Email"> </div> <div class="input-group margin-bottom-20"> <span class="input-group-addon"> <i class="fa fa-lock"></i> </span> <input type="password" name="password" class="form-control" placeholder="Password"> </div> <div class="row"> <div class="col-md-6"> <label class="checkbox"> <input type="checkbox">Stay signed in</label> </div> <div class="col-md-6"> <button class="btn btn-primary pull-right" type="submit">Login</button> </div> </div> </form> </div> </div> </body> </html> url.py from views import signin from django.contrib.auth import views as auth_views from django.conf.urls import url from django.contrib.auth.views import login … -
Traversing json array in python
I'm using urllib.request.urlopen to get a JSON response that looks like this: { "batchcomplete": "", "query": { "pages": { "76972": { "pageid": 76972, "ns": 0, "title": "Title", "thumbnail": { "original": "https://linktofile.com" } } } } The relevant code to get the response: response = urllib.request.urlopen("https://example.com?title="+object.title) data = response.read() encoding = response.info().get_content_charset('utf-8') json_object = json.loads(data.decode(encoding)) I'm trying to retrieve the value of "original", but I'm having a hard time getting there. I can do print(json_object['query']['pages'] but once I do print(json_object['query']['pages'][0] I run into a KeyError: 0. How would I be able to, with python retrieve the value of original? -
select2 / django-autocomplete-light - same object shows up multiple times in result set
I use django-autocomplete-light and I want users to be able to search projects with either the projects number, head of project or titel of the project in an autocomplete field. As soon as I add a third "| Q" line, I get the same object multiple times in my result list. I started with just name and project ID - there I could solve the problem by adding a "if isdigit()". But now I want to add additionally a search in the projects titel. Again, adding the third line with an "| Q" option results in some items showing up several times in the result set (3-5 times). Any ideas what that could be? Can I somehow solve that or at lest reduce the result set in the end to just show each object once? Thank you! :) class SearchProjectAutocomplete(autocomplete.Select2QuerySetView): #todo: bug that show results 4-5 times when searched in titel def get_queryset(self): qs = PubmaPublikation.objects.filter(typid__in=[222,223,224]).filter(zeigen=1) qs = qs.order_by('-erstellungsdatum') qs = qs.prefetch_related('pubmapublikationperson_set__person') qs = qs.prefetch_related('pubmapublikationsprache_set') if self.q: if self.q.isdigit(): qs = qs.filter(Q(projektnummer__contains=self.q)) else: qs = qs.filter( (Q(pubmapublikationperson__rolle=1) & Q(pubmapublikationperson__person__vorname__icontains=self.q)) | (Q(pubmapublikationperson__rolle=1) & Q(pubmapublikationperson__person__nachname__icontains=self.q)) | (Q(pubmapublikationsprache__order=1) & Q(pubmapublikationsprache__titel__icontains=self.q)) ) #as soon as I add the last Q-line and have a searchstring … -
Django template inheritence
In my django app i have a base.html template as follows <!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="text/html;charset=utf-8"/> <title>{% block title %}{% endblock %}</title> {# ----------------- STATIC FILES -------------- #} {% load staticfiles %} <link rel="icon" type="image/x-icon" href="{% static 'images/tab_logo.ico' %}"/> {% block site_css %} <link href="{% static 'bootstrap/css/bootstrap.min.css' %}" rel="stylesheet" type="text/css"/> <link href="{% static 'core/css/style.css' %}" rel="stylesheet" type="text/css"/> {% endblock %} {% block extra_css %}{% endblock %} <meta name="viewport" content="width=device-width"> </head> <body> {% block navbar %} <!-- START NAV --> <nav role='navigation'> <a data-page="home" id="home" class="active" href="/">Home</a> <a data-page="blog" id="blog" href="{% url 'blog' %}">Blog</a> <a data-page="contact" id="contact" href="{% url 'contact' %}">Contact Us</a> <a data-page="about" id="about" href="{% url 'about' %}">About</a> </nav> <hr> {% endblock %} <!--start container--> <div class="container"> <div class="row"> <div class="span9"> <div id="content"> <br> {% block content %}{% endblock %} </div> </div> </div> </div> <!--end container--> <hr> {% include 'core/footer.html' %} {% block javascript %} <!-- Grab Google CDN's jQuery, with a protocol relative URL; fall back to local if offline --> <script src="{% static 'core/js/jquery-3.1.1.min.js' %}"></script> <script src="{% static 'bootstrap/js/bootstrap.min.js' %}"></script> <script src="{% static 'core/js/skin.js' %}"></script> {% endblock %} {% block add_js %} {% endblock %} </body> </html> I am trying to make separate template files for … -
Install django-CMS with django 1.6
recently I installed django-CMS following this tutorial. While on iOS the django-cms installer asks which django version you need (among other options), in Ubuntu 14.04 I do not get to choose and I end-up with django-CMS 3.3 and django 1.8. I need to use django-CMS under django 1.6. I already tried this answer but when running pip install djangocms-text-ckeditor Django 1.6 is uninstalled and the 1.9 version gets installed. How can I get back the options during the django-CMS installation? -
Passing JSON "safely" from Django to Javascript adds ' characters that can't be parse by the JSON.parse method
I am using the Django framework and I try to pass a list of JSON to my javascript. Here is how I proceeded: On the server-side (Python/Django): context['my_json_list'] = [{'aaa': 'rst', 'bbb': 'uvw'}, {'ccc': 'xyz'}] return context On the client-side (html/javascript): In the HTML: <script type="text/javascript"> app.init("{{my_json_list|safe}}"); In the JS: var app = (function ($) { return { init: function (my_json_list) { console.log(my_json_list); my_json_list = JSON.parse(my_json_list); } } } The console.log() prints out: [{u&#39;aaa&#39;: u&#39;rst&#39;, u&#39;bbb&#39;: etc... which does not seem "parsable" by JSON.parse since I get the following error: angular.js:11413 SyntaxError: Unexpected token u in JSON at position 2 Is it the proper way of doing what I want, if yes how to solve the parsing part on the JS-side? If no, what is the right way of doing what I want to achieve? -
List of countries using modelchoicefield django model forms
I need to show list of countries to my site users using modelchoicefield. When a user selects the country, the code of the country should be submitted back to the form instead of its name. Models.py class Countries(models.Model): country_code = models.CharField(primary_key=True, max_length=10, blank=True, null=True) country_name = models.CharField(max_length=100, blank=True, null=True) class Meta: managed = False db_table = 'countries' def __unicode__(self): return self.country_name class UserCountryTable(models.Model): user_id = models.CharField(primary_key=True, max_length=10) country_code = models.ForeignKey(Countries, models.DO_NOTHING, db_column='country_code', blank=True, null=True) class Meta: managed = False db_table = 'userbycountry' Forms.py class CountryForm(forms.ModelForm): country_name = forms.ModelChoiceField(queryset=Countries.objects.all()) class Meta: model = UserCountryTable fields = ['user_id', 'country_code'] What i want at the back (form output) {'user_id': u'3452345', 'country_name': u'0003'} -------> 0003 is the code for Australia (I should get this from Countries table) Country list shown to user -
django project with multiple users
I'm new in django 1.8 python 3.5 plz help me to solve my problem. I have three four user i.e admin,guest,vendor,property manager.so task is show a same loginform to all with different pages. means vendor has dashboard page after login, guest see the activities and hotel property which added by vendor and property manager etc. so any one help me. its my startup project. -
django python manage.py runserver exception
I created a django project and try to runserver i got following exception. (venv) root@61-cpp-release # python manage.py runserver Performing system checks... System check identified no issues (0 silenced). Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x7fd859357f28> Traceback (most recent call last): File "/root/venv/lib/python3.5/site-packages/django/utils/autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "/root/venv/lib/python3.5/site-packages/django/core/management/commands/runserver.py", line 124, in inner_run self.check_migrations() File "/root/venv/lib/python3.5/site-packages/django/core/management/base.py", line 437, in check_migrations executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) File "/root/venv/lib/python3.5/site-packages/django/db/migrations/executor.py", line 20, in __init__ self.loader = MigrationLoader(self.connection) File "/root/venv/lib/python3.5/site-packages/django/db/migrations/loader.py", line 52, in __init__ self.build_graph() File "/root/venv/lib/python3.5/site-packages/django/db/migrations/loader.py", line 203, in build_graph self.applied_migrations = recorder.applied_migrations() File "/root/venv/lib/python3.5/site-packages/django/db/migrations/recorder.py", line 65, in applied_migrations self.ensure_schema() File "/root/venv/lib/python3.5/site-packages/django/db/migrations/recorder.py", line 56, in ensure_schema with self.connection.schema_editor() as editor: File "/root/venv/lib/python3.5/site-packages/django/db/backends/sqlite3/schema.py", line 25, in __enter__ self._initial_pragma_fk = c.fetchone()[0] TypeError: 'NoneType' object is not subscriptable Please help me to find a solution.... -
Pass data from a template tag to a django view
I'd like to pass a parameter with data, like category_id=2 from my template to the view. Here is how I think it should work (which obviously doesn't)... The view def category_detail(request, category_id): return_list = Category.objects.filter(category_id=category_id) return render(request, 'expense_list.html', { 'expense_list' : return_list }) HTML in the template: <a href="{% url 'category_detail' category_id=2 %}">Blah</a> Urls file: url(r'^detail/(?P<category_id>[0-9]+)/$', views.category_detail, name='category_detail'), -
Transferring django binaryfiled data via post request
I am working with django rest framework and aws S3 storage. I am uploading video files to S3 bucket and saving the encryption key in django models' binaryfield format (a requirement of s3 storage). Now i need to pass this key to another remote django server using post request. When i pass the key using requests library, somehow it is changed when i extract it from post request on the other server and i am unable to use it. It would be highly appreciated if some tells me how to pass binaryfield data via post request using django requests library. My code for making post request is import requests enc_key = some_object.key # key is a models.BinaryField() data = {'enc_key' : enc_key} response = requests.post(url, data = data) while on the other server i extract enc_key from post request like this enc_key = request.POST['enc_key'] but this key is not usable anymore. -
Get data of foreign key relations in a Serializer Django:Rest Framework
I have the following models class Task(models.Model): task_name = models.CharField(max_length=255) task_description = models.TextField(blank=True, null=True) project_id = models.ForeignKey('Project') class Project(models.Model): project_name = models.CharField(max_length=255) project_description = models.CharField(max_length=255) I am writing a serializer for task class TaskSerializer(serializers.ModelSerializer): class Meta: model = Task fields = ( 'id', 'task_name', 'task_description', 'project_id', ) But i want the project name as well in the TaskSerializer which can be accessed using the project_id. How do i achieve this? -
how to install request library in django
I want to install the library request in django! I want to get the authenticated user name. MY django version is 1.10 my python version is 2.7 When in the models.py i insert "import request" generates the error. there are ways to install this library directly in django? -
How to know the full URL in django before the view?
My goal is to check if the domain name redirection is really working well. How to easily know the full URL in django before the view and even before routing if it is possible. Cheers -
Generate html document with images and text within python script (without servers if possible)
How can I generate HTML containing images and text, using a template and css, in python? There are few similar questions on stackoverflow (e.g.: Q1, Q2, Q3) but they offer solutions that (to me) seem overkill, like requiring servers (e.g. genshi). Simple code using django would be as follows: from django.template import Template, Context from django.conf import settings settings.configure() # We have to do this to use django templates standalone - see # http://stackoverflow.com/questions/98135/how-do-i-use-django-templates-without-the-rest-of-django # Our template. Could just as easily be stored in a separate file template = """ <html> <head> <title>Template {{ title }}</title> </head> <body> Body with {{ mystring }}. </body> </html> """ t = Template(template) c = Context({"title": "title from code", "mystring":"string from code"}) print t.render(c) (From here: Generating HTML documents in python) This code produces an error, supposedly because I need to set up a backend: Traceback (most recent call last): File "<input>", line 17, in <module> File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/template/base.py", line 184, in __init__ engine = Engine.get_default() File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/template/engine.py", line 81, in get_default "No DjangoTemplates backend is configured.") django.core.exceptions.ImproperlyConfigured: No DjangoTemplates backend is configured. Is there a simple way to have a template.html and style.css and a bunch of images, and use data in a python … -
"The view polls.views.index didn't return an HttpResponse object. It returned None instead." Error in Django
I am following the tutorial in Django documentation. I did exactly as it has said in the tutorial. ValueError at /polls/ When I load on browser "http://localhost:8000/polls/" I get this error: The view polls.views.index didn't return an HttpResponse object. It returned None instead. Request Method: GET Request URL: http://localhost:8000/polls/ Django Version: 1.10.1 Exception Type: ValueError Exception Value: The view polls.views.index didn't return an HttpResponse object. It returned None instead. Exception Location: /home/jack/anaconda2/envs/py3k/lib/python3.4/site-packages/django/core/handlers/base.py in _get_response, line 198 Python Executable: /home/jack/anaconda2/envs/py3k/bin/python Python Version: 3.4.5 Python Path: ['/home/jack/Documents/Django Learning/mysite', '/home/jack/anaconda2/envs/py3k/lib/python34.zip', '/home/jack/anaconda2/envs/py3k/lib/python3.4', '/home/jack/anaconda2/envs/py3k/lib/python3.4/plat-linux', '/home/jack/anaconda2/envs/py3k/lib/python3.4/lib-dynload', '/home/jack/anaconda2/envs/py3k/lib/python3.4/site-packages/Sphinx-1.4.1-py3.4.egg', '/home/jack/anaconda2/envs/py3k/lib/python3.4/site-packages/setuptools-23.0.0-py3.4.egg', '/home/jack/anaconda2/envs/py3k/lib/python3.4/site-packages'] Server time: Thu, 6 Oct 2016 10:32:20 +0000 -
How to get html select to show selected value?
When I choose a value from the drop down list, I want to display the selected value in the drop down list. My code bellow is changing the content of the value on my page when i choose a value, but the drop down list always display the same value, instead of display the value that I have chosen. I have tried so many different solutions, but I can not get It to work :(. The option value is inside a Django for loop. <div class="organizations"> <select id="select-organizations" name="forma" onchange="location = this.value;"> {% for role in user.person.roles.all %} <option value="/org:{{ role.organization.number }}"> {{ role.organization }} </option> {% endfor %} </select> </div> -
Django doesn't update after postgresql changes
I'm using Django 1.8 with PostgreSQL 9.5.4 and i have an issue. I've updated single column in all rows in a table (example : UPDATE table_name SET name=lower(name) When i check the Postgre database - everything is updated , but in Django (django admin) nothing is updated (i've tried restarting postgresql & django , but no success ) , any help ? -
Django no such column even after migrations
This is my model code class Poll(models.Model): created_at = models.DateTimeField(auto_now=True) edited_at = models.DateTimeField(auto_now_add=True) title = models.CharField(max_length=200,default="X vs Y") description = models.CharField(max_length=200,default="A poll") def __str__(self): return self.title class Item(models.Model): poll = models.ForeignKey('Poll',on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now=True) edited_at = models.DateTimeField(auto_now_add=True) name = models.CharField(max_length=200) type_of = models.CharField(max_length=200) description = models.TextField(max_length=1200) votes = models.IntegerField(default=0) def __str__(self): return self.name You see votes in Item model right. That's a problem. I use makemigrations migrate command. But I still get no such column error. -
Execute Javascript and css in Django template
I am exporting HTML to PDF via Weasyprint in my Django app. I have noticed that if I send the template html to front end and return that html to backend to export it to pdf, it prints perfectly. But if I directly send template html to Weasyprint, it messes up everything! No css, no javascript. This is how I'm using the template to generate html: template = loader.get_template('Reporting/reportTemplate.html') context = { "reportObj" : result[0] } htmlContent = (template.render(context, request)) response['message'] = htmlContent return JsonResponse(response) In my JS controller I assign the htmlContent to my div: $('#htmlContent').html(response.message); Then I return the generated html back to my Django function to print pdf HTML(string=htmlContent).write_pdf(target=response, stylesheets=[CSS(string=getCSS())]) This way it maintains the design and everything. But when I send htmlContent directly to Weayprint without sending it to front end, the design and coloring is gone! In my template, I even have included CSS and Javascript files like this: {% load static %} {% block content %} <link href="{% static "css/ion.rangeSlider.css" %}" rel="stylesheet"> <link href="{% static "css/ion.rangeSlider.skinHTML5.css" %}" rel="stylesheet"> <script type='text/javascript' src='{% static "scripts/ion.rangeSlider.js" %}'></script> <script type='text/javascript'> $(document).ready(function(){ var creditScore = $("#creditScore").html(); $("#rangeCS").ionRangeSlider({ type: "double", min: 0, max: 1000, step: 100, from: 0, to: creditScore, … -
Error ,coercing to Unicode: need string or buffer, list found
I am trying to render a template in django but it brings this error in the browser "coercing to Unicode: need string or buffer, list found".It specifically points to line 25 which is code that points to a static file.Here is the code for the template. base.html {% load staticfiles %} <html> {% block content %} <head> </head> <body ng-app = "{% block ng_app %}example.app.static{% endblock %}"> <div class = "container"> <div class = "content" ng-controller = "{% block ng_controller %}AppController{% endblock %}"> {% verbatim %} <div class = "panel" ng-repeat = "post in posts"> <div class = "panel-heading clearfix"> <h3 class = "panel-title">{{post.title}}</h3> <author class ="pull-right">{{post.author.username}}</author> </div> <p class = "well">{{post.body}}</p> </div> {% endverbatim %}</div> {% endblock %} </div> {% block js %} <script src = "{%static "underscore/underscore.js" %}"></script> <script src = "{%static "angular/angular.js" %}"></script> <script src = "{%static "angular-resource/angular-resource.js" %}"></script> <script src = "{%static "src/js/app.basic.js" %}"></script> {% endblock %} </html> -
Will ASP.NET core be production-ready by the end of Q1 2017?
We are considering using .NET core on a new project. We need to use: Docker Websocket ORM Json Web Token Is .NET core a good choice? -
What is the best practice to use udp data stream inside a Django project. And what about the data storage
I am implementing a backend for a multiplatform app. Right now we are trying to get the communication from a certain device under windows. The device sends all the data through UDP. We need the data in real time. Also I want to store it. Is there any pipeline that suits the need? -
How to add a checkbox in a list similar to the Django admin site
The admin site in Django displays a list of db entries, with a checkbox next to each entry. There's then some actions that can be performed on the selected items (mostly delete) How does the admin site achieve this and what is the easiest way I can replicate it in my site? Is there something built in Django that can do this? If guess I can just output a checkbox for each item in the list with its value set to the id of the db entry. Then when the data gets posted to me, I can construct a list with the selected IDs and do a "in" db lookup to get all the selected items and perform the appropriate action. Not sure if there is an easier/better way though?