Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to obtain dicts key and values in django template
I have a dictionary: {'m': 'm', 'c': None, 's': None, 'n': None, 'a': 'a', 'x': None, 'b': None, 'l': None, 'u': None, 'o': 'o', 'q': None, 'i': None, 'f': None, 'z': None, 'e': None, 't': 't', 'h': None, 'y': None, 'v': None, 'p': None, 'k': None, 'g': None} I'd like to hand the key value pairs that have the value None differently than the key value pairs that have the letters. I have been struggling to figure this out so any help is greatly appreciated! Heres what I have so far for the template <table align="center" cellpadding="4px"> <tr> {% for key in index_display.key() %} {% if index_display[key] = None %} <td><a href="">{{ key }}</a></td> <td id="partners_nav_bracket">|</td> {% else %} <td><a href="{{ value }}">{{ key }}</a></td> <td id="partners_nav_bracket">|</td> {% endif %} {% endfor %} </tr> </table> This however throw an error: Could not parse the remainder: '()' from 'index_display.key()' -
How to ensure Django model saves before Celery task execution?
I have a Django 1.11 + MySQL + Celery 4.1 project where a view creates a new user record, and then kicks off a Celery task to perform additional long-running actions in relation to it. The typical problem in this case is ensuring that the user creation is committed to the database before the Celery task executes. Otherwise, there's a race condition, and the task may try and access a record that doesn't exit if it executes before the transaction commits. The way I had learned to fix this was to always wrap the record creation in a manual transaction or atomic block, and then trigger the Celery task after that. e.g. def create_user(): with transaction.atomic(): user = User.objects.create(username='blah') mytask.apply_async(args=[user.id]) @task def mytask(user_id): user = User.objects.get(id=user_id) do_stuff(user) However, I still occasionally see the error DoesNotExist: User matching query does not exist in my Celery worker logs, implying my task is sometimes executing before the user record gets committed. Is this not the correct strategy or am I not implementing it correctly? -
validation django model (BaseProduct)
I am trying to validate this model, but I am struct with that so, can someone please pick it up and help me out I need to validate CharFiled, DecimalField and ImageField models.py class BaseProduct(models.Model): PRODUCT_TYPE = ( ('normal', 'Normal'), ('combo', 'Combo'), ) id = models.AutoField(primary_key=True) name = models.CharField(max_length=200) type = models.CharField(max_length=200], choices=PRODUCT_TYPE, blank=True, default='normal', help_text='Product availability') price = models.DecimalField(max_digits=6, decimal_places=2, default="") image = models.ImageField(upload_to='image/product/', blank="True") class Meta: verbose_name = "product" def __str__(self): return '%s, %s, %s' % (self.name, self.type, self.price) -
Change rendering of a particular CharField in Django
I have a model BankAccount. BankAccount model contains CharField IBAN which is a International Bank Account Number. I use {{ bank_account.IBAN }} in multiple templates. It's stored as a string without spaces but I want to change it's template rendering such that every 4 characters are followed by zero. SK121234123412341234 will be rendered as SK12 1234 1234 1234 1234 I could probably create some TemplateTag or TemplateFilter but I'm curious if there is a way to change it in BankAccount model. For example create my own IBANField (overriding CharField) so I don't have to surrounding IBAN variable by tags or filters. class BankAccount(models.Model): IBAN = models.CharField(max_length=40, ... ) ... Didn't find rendering methods here: https://docs.djangoproject.com/en/1.11/howto/custom-model-fields/ -
django channels working in runserver but "Still in CONNECTING " & "ERR_CONNECTION_TIMED_OUT" in production, probably related to SSL
I am following "getting started" in the django channel docs as well as "django channels form the ground up" tutorial in the django, using REDIS, NGINX and GUNICORN on digital ocean. Based on browser console errors, I modified command to wss to test in browser: socket = new WebSocket("wss://" + window.location.host + ":8001/chat"); Then the rest copied: socket.onopen = function() { socket.send("hello world"); } // Call onopen directly if socket is already open if (socket.readyState == WebSocket.OPEN) socket.onopen(); The terminal response to runserver 0.0.0.0:8000 : System check identified no issues (0 silenced). October 30, 2017 - 10:40:10 Django version 1.11, using settings 'dojos.settings' Starting Channels development server at http://0.0.0.0:8000/ Channel layer default (channels_panel.apps.DebugChannelLayer) Quit the server with CONTROL-C. 2017-10-30 10:40:10,203 - INFO - worker - Listening on channels http.request, websocket.connect, websocket.disconnect, websocket.receive 2017-10-30 10:40:10,205 - INFO - worker - Listening on channels http.request, websocket.connect, websocket.disconnect, websocket.receive 2017-10-30 10:40:10,206 - INFO - worker - Listening on channels http.request, websocket.connect, websocket.disconnect, websocket.receive 2017-10-30 10:40:10,208 - INFO - server - HTTP/2 support not enabled (install the http2 and tls Twisted extras) 2017-10-30 10:40:10,208 - INFO - server - Using busy-loop synchronous mode on channel layer 2017-10-30 10:40:10,209 - INFO - server - Listening … -
lazy reference: doesn't provide model user?
Currently I'm using Django 1.11 and Python 3.6. I'm attempting to create a custom user model with a new application that authenticates with LDAP, but i'm greeted with the following error message. raise ValueError("\n".join(error.msg for error in errors)) ValueError: The field admin.LogEntry.user was declared with a lazy reference to 'accounts.user', but app 'accounts' doesn't provide model 'user'. Settings.py Installed Apps, Auth Backends, and Auth_User Model: INSTALLED_APPS = [ 'django_python3_ldap', 'django_extensions', 'django_filters', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'accounts', ] AUTHENTICATION_BACKENDS = ( 'django_python3_ldap.auth.LDAPBackend', 'django.contrib.auth.backends.ModelBackend', ) AUTH_USER_MODEL = "accounts.User" Admin.py: from django.contrib import admin from django.conf import settings from .models import User # Register your models here. admin.site.register(User) Below is my models.py: from __future__ import unicode_literals from django.utils import timezone from django.contrib.auth.models import (AbstractBaseUser,PermissionsMixin) from django.db import models from django.forms import ModelForm class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True) username = models.CharField(max_length=25, unique=True) first_name = models.CharField(max_length=40) last_name = models.CharField(max_length=140) date_joined = models.DateTimeField(default=timezone.now) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) facility = models.CharField(max_length=140) jobdescription = models.CharField(max_length=140) positiondescription = models.CharField(max_length=140) USERNAME_FIELD = "username" -
Python calendar.month_name How to Skip 0-index
So I am trying to use the Python calendar API to loop through the months of the year. Let's say the current month is January (month "1"). If I do calendar.month_name[1-1] (A month before January), the result I get is an empty string "" - seemingly because month "0" doesn't exist. However, if I do calendar.month_name[1-2], the resulting -1 value leads to December being returned. So my question is how do I get a month_name[] parameter of 0 to return the month before it? -
is there any implementation for a field datetime-range with Django and Mysql?
I need create a new Field in my DB class Driver(models.Model): name = models.CharField(max_length=250) last_name = models.CharField(max_length=250) licence_date = models.DatetimeFieldRange(blank=True , null=True) In this field I going to save two dates( start - end) thanks -
Django: How to scale system with highthrought request?
I'm going to design an analysis system as Google analytic. I want use Django for webserver and front end. But I really need a high throughput system, with thousands of requests per second and respond in 10-15 milisecond. I'm not experience for do that. So please help me to make clear something: 1) Should we use kafka for handle incoming request? I just use for weblog, so I just one topic for pub/sub. So will kafka help scale my system? How about if I just build kafka on standalone server? Please give me idea about kafka. 2) Without kafka, could we have any other solutions? Please help or sharing any idea that you know. Thanks & Best Regards, Phuong Hoang -
Django QuerySet.exclude(): Why are all excluded?
I have a situation like this: ids = [None, None, None] foo = Foo.objects.filter(common=True).exclude(id__in=ids) This seems to exclude all always. Why is id of id__in threated as None in this case? pk__in didn't work either. I expect it to not exclude anything as all objects have valid id's. foo = Foo.objects.filter(common=True) Returns all objects like expected. -
Django - Supervisor : excited too quickly
I try to deploy my website in Django+Supervisor+NGINX on Ubuntu server 16.04. Here is my .conf (supervisor): [program:sitepro] command = /home/user/sitepro/bin/gunicorn sitepro.wsgi:application --bind mywebsite.fr:8002 user = user autostart = true autorestart = true My NGINX config file : server { listen 80; server_name .mywebsite.fr; charset utf-8; root /home/user/sitepro/site/sitepro; access_log /home/user/sitepro/site/logs/nginx/access.log; error_log /home/user/sitepro/site/logs/nginx/error.log; location /static { alias /home/user/sitepro/site/static; } location / { proxy_set_header Host $http_host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_redirect off; proxy_pass http://127.0.0.1:8002; } } When I try to launch gunicorn on the root of my project, everything goes right : (sitepro) user@mybps:~/sitepro/site$ gunicorn sitepro.wsgi:application --bind mywebsite.fr:8002 [2017-11-01 16:09:37 +0000] [1920] [INFO] Starting gunicorn 19.7.1 [2017-11-01 16:09:37 +0000] [1920] [INFO] Listening at: http://79.137.39.12:8002 (1920) [2017-11-01 16:09:37 +0000] [1920] [INFO] Using worker: sync [2017-11-01 16:09:37 +0000] [1925] [INFO] Booting worker with pid: 1925 I've done a supervisorctrl reread and update (worked). And if I make supervisorctl status sitepro sitepro FATAL Exited too quickly (process log may have details) And if I access my website I've got the "Welcome to Nginx" default page. I've tried many tutorials for deploy django : I'm lost and tried many things. Could someone give me a simple and fast tutorial to deploy Django that he used for his … -
Correct NoReverseMatch error with authentication algorithm
I want to allow the user to reset password when the user is signed out and cannot remember the password. I am using the django authentication framework and have created the reset_password and password_reset_done mappers. Issue : Though I have created the password_reset_done function I continue to get the below error. Is there a step that I missed that is causing this error? I do not know what I have done wrong. I have posted all the code that I think is relevant to what I attempting to do. Here is the code : relative urls.py from django.conf.urls import url from . import views from django.contrib.auth.views import login, logout, password_reset, password_reset_done urlpatterns = [ url(r'^$', views.vedic_view, name = 'vedic_home_view'), url(r'^login/$', login, {'template_name' : 'exist/login.html'}, name = 'login'), url(r'^logout/$', logout, {'template_name' : 'exist/logout.html'}, name = 'logout'), url(r'^register/$', views.register_view, name = 'register'), url(r'^profile/$', views.view_profile, name = 'view_profile'), url(r'^profile/edit/$', views.edit_profile, name = 'edit_profile'), url(r'^change-password/$', views.change_password, name = 'change_password'), url(r'^reset-password/$', password_reset, name = 'reset_password'), url(r'^reset-password/done/$', password_reset_done, name = 'password_reset_done') ] main urls.py from django.conf.urls import url from django.contrib import admin from django.conf import settings from django.conf.urls.static import static urlpatterns = [ url(r'^admin/', admin.site.urls), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) from django.conf.urls import include from django.views.generic import … -
Cannot connect django 1.11.6 to MS SQL Server using django-pyodbc-azure
I am working on a django app which needs to connect to MS SQL Server 2008. I use django-pyodbc-azure backend. Environment: Ubuntu 16.04 Apache 2.4 python 3.5.2 django 1.11.6 django-pyodbc 1.1.1 django-pyodbc-azure 1.11.0.0 I have also installed dependents: unixodbc unixodbc-dev tdsodbc freetds-dev In /etc/freetds/freetds.conf: [sqlserver] host = mysqlserverhost.com port = 6789 tds version = 8.0 In /etc/odbc.ini: [sqlserverdatasource] Driver = FreeTDS Description = ODBC connection via FreeTDS Servername = sqlserver Database = test TDS_Version = 8.0 In /etc/odbcinst.ini: [ODBC] Trace = Yes TraceFile = /tmp/odbc.log [FreeTDS] Description = TDS driver (Sybase/MS SQL) Driver = /usr/lib/x86_64-linux-gnu/odbc/libtdsodbc.so Setup = /usr/lib/x86_64-linux-gnu/odbc/libtdsS.so CPTimeout = CPReuse = FileUsage = 1 Then I tested the connection with the following. import pyodbc db = pyodbc.connect('DRIVER={FreeTDS};SERVER=mysqlserverhost.com,6789;DATABASE=test;UID=admin;PWD=password;TDS_Version=8.0') cursor = db.cursor() cursor.execute("SELECT @@version;") row = cursor.fetchone() while row: print(row[0]) row = cursor.fetchone() I can see the version of SQL Server from the above codes. Microsoft SQL Server 2008 R2 (RTM) - 10.50.1600.1 (X64) Apr 2 2010 15:48:46 Copyright (c) Microsoft Corporation Enterprise Edition (64-bit) on Windows NT 6.2 <X64> (Build 9200: ) In django projects settings.py, I configured the database backend. DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'NAME': 'test', 'USER': 'admin', 'PASSWORD': 'password', 'HOST': 'mysqlserverhost.com', 'PORT': '6789', 'OPTIONS': { … -
Query Database Table Without Using Foreign Key Django Postgresql
I am trying to query a table where I have many records with the same name, on purpose. In my example, I'm using the make of the car, and unfortunately I've already ruled out using a foreignkey. Long story. Anyway, I've been able to determine that I can query the table using a ModelChoiceField and using the distinct command as I'm using Postgresql as shown below: class Vehicle(forms.Form): dropdown = forms.ModelChoiceField(queryset=Car.objects.none()) def __init__(self, *args, **kwargs): super(Vehicle, self).__init__(*args, **kwargs) self.fields['dropdown'].empty_label = '' qs = Car.objects.distinct('vehicle_make') The code above does, what I need related to the dropdown, it limits the ModelChoiceField to just the unique values of the vehicle_make of the car. The challenge is when I go to try to display all of the records with that vehicle_make in my template. I've tried to do a Detail View, but it is only showing me that individual record. That make sense since detail view is just for that record, but I'm trying to figure out how to query the table to show me all of the records with that vehicle_make. I've explored the ChoiceField as well, but can't seem to get this to work either. I've tried several variations of the code … -
Not able to run django-admin script on ubuntu
When I ran the following command : django-admin startproject project_name I got the following error : The program 'django-admin' is currently not installed. You can install it by typing: sudo apt install python-django-common I did what it told me to and nwo I get the following error: Cannot find installed version of python-django or python3-django. on running the same command, I am not able to understand if I had installed django , then why was django-admin script not installed Note that django is installed which is verified by the following: $ python -c "import django; print(django.get_version())" 1.7 -
JavaScript VS Django(python)
I started to learn django not long ago and I was wondered if you can do the same things (such as vars,Forms,etc..) as there in JavaScript in Django ? I mean I did learn python for few months and have some basic knowledge in it. I never tried JS (I am learning java). Should I stay with Django and do the same things or start learning js :P Thanks in advance. -
Python - File or Folder Content Version Control
We're using CKEditor to generate HTML content when author writes his book. We're storing that content to a separate HTML file on the disk using python-django. But now, we have got a requirement from client to show the history/revision of the files (list of time stamps in a sidebar whenever author has pressed ctrl+s), like the Eclipse does: I am planning to use diff by taking intersection of the html texts stored at 2 different times. But I am not getting any idea about how to take the diff of images, audios and videos. Any idea how git, eclipse or Vesrsion control systems do that? Do they use any kind of encoding such as SHA to store it on the disk? Please suggest if any other method I can use to do this. -
Django-graphene: how to filter with an OR operator
I am pretty new with both Django and Graphene, and couldn't get around a problem which might be fairly simple, but I had no luck with the docs or google to get an answer. Let's say I have the following model: class Law(models.Model): year = models.IntegerField(default=None) number = models.IntegerField(default=None) description = TextField(default=None) body = models.TextField(default=None) And the following schema: class LawType(DjangoObjectType): class Meta: model = models.Law filter_fields = { "year": ["exact"], "number": ["exact"], "description": ["contains"], "body": ["icontains"], } interfaces = (graphene.Node, ) class Query(graphene.AbstractType): all_laws = DjangoFilterConnectionField(LawType) def resolve_all_laws(self, args, context, info): return models.Law.objects.all() How do I make a query or define a FilterSet class so that it will return a list of objects such that a word is found in the description or in the body? { allLaws(description_Icontains: "criminal", body_Icontains: "criminal") { edges{ node{ year number } } } } I couldn't find an answer in the graphene-django documentation nor in the django-filter documentation. Any clues? Thanks in advance -
How to accommodate a querystring in django mock
I'm completely stumped on this in that I don't even know what to google. I'm not well versed in python testing (I work mainly in javascript). I have an endpoint in python/django that I added a querystring to. This is the endpoint (I've changed some names to make it more generic): class ThingSeriesView(APIView): """ Ajax Request for just the Thing Series data """ renderer_classes = (JSONRenderer, ) def get(self, request, pk, **kwargs): # pylint: disable=invalid-name """ :param request: :param pk: :return: """ thing = get_object_or_404(models.Thing, pk=pk) frequency = float(request.GET.get('frequency', '1.0')) serializer = ChartDataSeriesSerializer( thing.get_series(frequency)) return Response(serializer.data) The line I added was (and this is causing the problem): frequency = float(request.GET.get('frequency', '1.0')) And thing.get_series was originally just passed '1.0' for everything. This is fine, and it does what I need to it to, however it breaks a test: class TestThingSeriesView(object): """ Test the ThingSeries view """ def test_get(self): thing = models.Thing() # pylint: disable=line-too-long with patch('main.endpoints.get_object_or_404', new_callable=Mock) as mock_get_obj,\ patch('main.endpoints.Response', new_callable=Mock) as mock_response,\ patch.object(thing, 'get_series') as series_method: endpoint = endpoints.ThingSeriesView() mock_get_obj.return_value = thing assert endpoint.get(Mock, 'foo') == mock_response.return_value mock_get_obj.assert_called_once() series_method.assert_called_with(1.0) This is the error I get: > frequency = float(request.GET.get('frequency', '1.0')) E AttributeError: type object 'Mock' has no attribute 'GET' How … -
signup error in django
i have a problem i created a signup page to add users to my django but the problem is when i used a code to check usernames from the existing usenames and tell the users to change the username if someone already used that user and here is my code snippet: from signup.html from django.shortcuts import render from django.contrib.auth.models import User # Create your views here. def signup(request): if request.method == 'POST': if request.POST.get('password1') == request.POST.get('password2'): try: user=User.objects.get(username=request.POST.get('username')) return render (request,'accounts/signup.html',{'error':'usename has been aleady used'}) except User.DoesNotExist: User.objects.create_user(username=request.POST.get('username') , password=request.POST.get('password1')) return render (request,'accounts/signup.html') else: return render (request,'accounts/signup.html',{'error':'passwod didnt match'}) else: return render (request,'accounts/signup.html') and i dont know whats wrong with this code but when i open localserver:8000/signup and after entering all those deatils and submitting i have been always getting an error as the password is not same in both cases but if i remove the code lines that checks regarding username then i can submit and add users to my website -
Django filter by list of foreign keys
I'm new to Django and Python overall so bare with me, please. I'm also using fixtures for mock data. I have tags.json that simply contains all possible tags like so { "model": "app.tag", "pk": 1, "fields": { "name": "Foo" } }. I also have links.json that contains links like this { "model": "app.link", "pk": 1, "fields": { "title: "Lorem ipsum", ... "tags": [1, 3, 2], ... } } In my views.py I have my_tags argument which is a string that I split(','). So when I go to http://www.example.com/tags/foo,bar I end up with ['foo','bar'] in my view. So what I want to do is something like Link.objects.filter(tags: my_tags) so that I only receive links that have both foo and bar tags. Can someone help me out and explain how to achieve this? -
VSCode starts up when I use ".py" extension with CMD commands
I don't know when and how it started but now I have such a glitch: open CMD enter python command: "django-admin.py help" Visual Studio Code starts up and opens manage.py for editing. The CMD command itself does not return anything. on the other hand, if I enter: "django-admin help" (without .py) the CMD shows help and VSCODE does not react in any way. What is this magic? How to change VSCODE reaction to .py mentioning? -
What form field type to use for arrays (lists)
I'm expecting json data to be submitted to my form, with one field being an array of up to N strings of M chars each. The model uses a django.contrib.postgres.fields.ArrayField - what type of field should I declare it as in the form? -
ProgrammingError at "url" relation "app_model" does not exist LINE 1: SELECT COUNT(*) AS "__count" FROM "app_model"
I've searched every Stack Overflow question on this error but none of the responses helped. I'm getting this error when trying to access the admin page of this particular model (AgentBasicInfo). 'manage.py makemigrations' works fine. 'manage.py migrate' also works fine. 'manage.py runserver' works fine, the whole website works fine until I try to go onto the admin page of this model. The app is correctly installed in INSTALLED_APPS in settings.py. I am using Postgres for the database. I have tried... Deleting migrations and re-running makemigrations/migrate Deleting the entire migrations folder for this app and rerunning makemigrations/migrate Deleting all the migrations from all my apps and re-running makemigrations/migrate I have tried running 'manage.py migrate' and 'mangae.py migrate app_name'. I still get the same error. This model (see code below) is quite basic. I have several other models in my project and they work just fine in the admin, but just this particular model doesn't work. models.py class AgentBasicInfo(models.Model): preferred_email = models.EmailField() office_phone_number = models.IntegerField() brokerage_of_agent = models.CharField(max_length=50) agent_title = models.CharField(max_length=20) def __str__(self): return self.preferred_email settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'postgres', 'USER': 'postgres', 'PASSWORD': 'lagger123', 'HOST': '127.0.0.1', 'PORT': '5432', } } -
Using django with mysql fails
Am new to django and i wanted to setup mysql instead of the default sqlite so i have DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', //..mysql settings here } } Now am getting an error ImproperlyConfigured: Error loading MySQLdb module: No module named 'MySQLdb'. Did you install mysqlclient or MySQL-python? I have run sudo apt-get install libmysqlclient-dev which runs successifully but doesnt clear the improperly configured error In my Computer(Linux) i already have set apache2 and mysql server. What could be wrong or how do i resolve this?