Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to make search form in Django?
How to make function search which filter record from text boxes in forms? The function will execute when button 'search' is clicked and the results will appear in a template table. I need a sample code (form/view/model/template) to adapt it with my forms. Any suggestion? Thank you in advance. -
Django project - 1.4 to 1.8?
I'm taking over somebody else's project that was coded using Django 1.4 and Python 2.6. Pretty old, i know. I want to upgrade it to Django 1.8 and Python 2.7. After installing Python 2.7 and Django 1.8 (using pip), i noticed that the project itself didn't change and it's still "set" to work with Django 1.4 and Python 2.6. What is the process i have to go through to make that kind of upgrade? -
Django with Docker Module NOT found Error
I am Trying to build the Django app with Docker.My application will run on local server however when i try to migrate with docker it throw Module Not Found Error This is my requirements.txt djangorestframework==3.7.0 Django==1.11.5 #import_export==0.5.1 django-csvimport==2.2 psycopg2 This is my docker-compose.yml`. docker-compose.yml version: '3' services: web: build: . command: python djangorest/manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" This is my Dockerfile FROM python:3.6 ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code ADD requirements.txt /code/ #COPY . /code/ RUN pip install -r requirements.txt ADD . /code/ I am get following error when i pass this cmd docker-compose run web python djangorest/manage.py migrate docker-compose run web python djangorest/manage.py migrate Traceback (most recent call last): File "djangorest/manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 338, in execute django.setup() File "/usr/local/lib/python3.6/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/local/lib/python3.6/site-packages/django/apps/registry.py", line 85, in populate app_config = AppConfig.create(entry) File "/usr/local/lib/python3.6/site-packages/django/apps/config.py", line 120, in create mod = import_module(mod_path) File "/usr/local/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 941, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed … -
How do I replace a string variable
I have a code as follows with open(f1) as f: userid=f.read().replace('0', str(instance.id)) The above works well. Now, the variable userid as a string has character In will like to replace. I tried this code and is given errors shown below. Please note: the variable the_user.phonelist is a python LIST. I will like to replace the character [] with the list. ans = userid.replace('[]', the_user.phonelist) Error: Can't convert 'list' object to str implicitly -
How do you hide a field if other field's condition is not met in django?
So if I have this code in my models.py class Computer(models.Model): brand = models.CharField(max_length=225) how do I show either of the following additional field in my django admin depending on the value of brand above? mac_os = models.CharField(max_length=225) windows_os = models.CharField(max_length=225) linux = models.CharField(max_length=225) e.g. if brand == HP only the field for windows_os or linux will be shown when you try to input your data in the admin and will the hide field for mac_os. thanks so much.. :) -
Limit django for loop in the template or the view for better performance?
I have a for loop on my template. I only want to display the first 3 items in the loop for a blog. At present there are only 20 blog entries, but if the blog entries are say 500 or more, from a performance perspective, is it better to limit the loop in the views.py code or in the template code? Here is the loop limit in the views.py file: blog_latest_entries = BlogDetails.objects.filter(blog_date_published__lte=date_now).order_by('-blog_date_published')[:3] ..... return render(request, 'page.html', { 'blog': blog_details_latest_entries, Here is the limit in the template code: {% for blog in blog|slice:"3" %} Which option is best for performance. I suspect the views.py approach, but I would like my suspicion backed up by someone with real knowledge. Thanks. -
Django: how to retain context object passed to the render function for another render
I pass a context dictionary called dict_context in my render function and it renders using the data just fine. return render(request, 'myapp/track.html', dict_context) Now, in the rendered page, I have a button that will POST and I want to use the context dictionary again, but I receive this error: UnboundLocalError at /track_containers_import_data local variable 'dict_context' referenced before assignment How can I reuse dict_context in the next render? I thought contexts are saved automatically in the sessions. -
Using python async / await with django restframework
I am just upgrading an older project to Python 3.6, and found out that there are these cool new async / await keywords. My project contains a web crawler, that is not very performant at the moment, and takes about 7 mins to complete. Now, since I have django restframework in place already to access data of my django application, I thought it would be nice to have a REST endpoint where I could start the crawler from remote with a simple POST request. However, I don't want the client to synchronously wait for the crawler to complete. I just want to straight away send him the message that the crawler has been started and start the crawler in the background. from rest_framework import status from rest_framework.decorators import api_view from rest_framework.response import Response from django.conf import settings from mycrawler import tasks async def update_all_async(deep_crawl=True, season=settings.CURRENT_SEASON, log_to_db=True): await tasks.update_all(deep_crawl, season, log_to_db) @api_view(['POST', 'GET']) def start(request): """ Start crawling. """ if request.method == 'POST': print("Crawler: start {}".format(request)) deep = request.data.get('deep', False) season = request.data.get('season', settings.CURRENT_SEASON) # this should be called async update_all_async(season=season, deep_crawl=deep) return Response({"Success": {"crawl finished"}}, status=status.HTTP_200_OK) else: return Response ({"description": "Start the crawler by calling this enpoint via post.", "allowed_parameters": … -
django slow POST response
I've been trying to learn python and django by creating a server on an raspberry pi 3 to accept data from some IoT projects around the house. I have set up the server and successfully managed to POST data to a url. However, I'm seeing that that the POST request takes about 1s. This is far too slow if I want several IoT devices feeding data back to the pi. @csrf_exempt def update(request): if request.method == "POST": key = request.POST.get("key", "") if key == settings.API_KEY: deviceID = request.POST.get("id", "") format = request.POST.get("format", "") datatype = request.POST.get("datatype", "") data = request.POST.get("data", "") fields = [format,datatype,data] WriteFields(deviceID,fields) return JsonResponse({"result": "received"}) else: return JsonResponse({"error": "invalid_key"}) return JsonResponse({"error": "no_post"}) This code is probably awful as I'm new django and python... I ran a quick script to test the POST rate import requests for i in range(100): r = requests.post("http://heimdall:8000/sensors/update/", data={'key': 'testkey', 'id': '123456', 'format': 'temp', 'datatype': 'c', 'data': '12'}) print(r.status_code, r.reason) The timestamps in the django terminal were showing the response about every 1s. To eliminate the pi being the bottle-neck I ran the same django project on my i3 based Plex media server and I get similar results. I've also tested sending POST … -
Django displaying data from database in template
I'm having some trouble displaying data from my database on the template in django model: class CityInfo (models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=200) landmark_type = models.CharField(blank=True, max_length=30) business = 'Business' student = 'Student' tourist = 'Tourist' def __str__(self): return self.name view: def itemget(request): data=CityInfo.objects.all() return render(request,'CityApp/infopage.html', {'data': data}) infopage.html: <ul> {% for item in data %} <li> <h1>{{ item.name }}</h1> </li> {% endfor %} <ul> The above html results in a blank list and I have no idea why. -
Import Error : from django.core.handlers.wsgi import STATUS_CODE_TEXT
I am super new with django and python and I'm having trouble getting the django rest framework integrated into my project. I've got my model, serializer, and api in order, I think but when I attempt to run the server I get a string of errors: from django.core.handlers.wsgi import STATUS_CODE_TEXT ImportError: cannot import name STATUS_CODE_TEXT Anyone have an idea of how to fix this or what I am doing wrong? Thanks! python version: 2.7.14 django version: 1.11.6 rest framework version: 3.1.1 Here is code from my site and the app in question just in case: settings.py INSTALLED_APPS = [ ... 'rest_framework', } models.py # -*- coding: utf-8 -*- from __future__ import unicode_literals # Create your models here. from django.db import models from django.utils.encoding import python_2_unicode_compatible @python_2_unicode_compatible class Employee(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) supervisor = models.ForeignKey('self', blank=True, null=True) is_active = models.BooleanField(default=True) is_supervisor = models.BooleanField(default=False) def __str__(self): return "{}".format(self.first_name + ' ' + self.last_name) api.py from rest_framework.generics import ListAPIView from .serializers import EmployeeSerializer from .models import Employee class EmployeeApi(ListAPIView): queryset = Employee.objects.all() serializer_class = EmployeeSerializer serializers.py from rest_framework import serializers from .models import Employee class EmployeeSerializer(serializers.ModelSerializer): class Meta: model = Employee urls.py from django.conf.urls import include, url from django.contrib import … -
Postgres: failed to set up event for socket: error code 10038
For reference, I've been tackling this problem for a couple of hours and have found a couple of related resources like failed-to-set-up-event-for-socket-error-code-10038-in-postgres 10038-socket-error postgresql-9-4-server-closed-the-connection-unexpectedly psql-server-closed-the-connection-unexepectedly But unfortunately, I still haven't been able to resolve this issue. I'm creating a Django REST web application with Postgres as my database and Windows as my OS. However, both within my django server and simply using psql, I sometimes get the error "server closed the connection unexpectedly", but without any reproducible pattern. Checking the postgres logs, the error that repeatedly comes up when this happens is: FATAL: failed to set up event for socket: error code 10038 But I haven't been able to find out what's been causing it. Some of the things I've tried are: Uninstalling and reinstalling on both Postgres 9.6 and 10 Restarting after installation (seemed to help for a little bit) Disabling antivirus & firewall Adding host all all 192.168.1.0/24 md5 to my pg_hba file Again, this connection drop happens in my django app, in pgadmin IV, and psql on the command line. Error happens in both successful and unsuccessful psql authentications. Database is set to port 5432, and PATH is correctly set to the postgres bin folder. psycopg2 is … -
Backup DB Django MysqlDump
Good afternoon, I have an application in Django 1.10 where I need to create a backup of the bd, this copy should be made when the user clicks on a button that will be placed in a template and will download the copy in the Team of the user. In my views.py I have the following. def backup(request): subprocess.Popen("mysqldump -u root -p12345 victimas > /home/proyecto/backup.sql") subprocess.Popen("gzip -c /home/proyecto/backup.sql > /home/proyecto/backup.gz") dataf = open('/home/proyecto/backups/backup.gz', 'r') return HttpResponse(dataf.read(), mimetype='application/x-gzip') But I get the error [Errno 2] No such file or directory: django mysqldump Doing this directly from the console creates the file for me, and check the permissions of the folder. I appreciate your collaboration -
Deploying Django app on Ubuntu 16.04 apache2 with mod_wsgi
I am trying to deploy my django app to Ubuntu 16.04 running Apache with mod_wdgi. I have the apache server setup correctly (i think) but I am running into a issue when apache trying to run my "prod_wgsi.py" script, it is trying to import the wrong settings module. I am able to start the python interpreter with "python -i prod_wsgi.py" load my settings file and run django.setup(). File structure NOCduncan website ___init__.py manage.py prod_wsgi.py website settings ___init__.py dev.py prod.py base.py templates ___init__.py prod_wsgi.py import os from django.core.wsgi import get_wsgi_application import sys import site # Add the site-packages of the chosen virtualenv to work with site.addsitedir('/home/biffduncan/.virtualenvs/nocduncanenv/lib/python3.5/site-packages') # Add the app's directory to the PYTHONPATH paths = [ '/home/biffduncan/opt/NOCduncan', '/home/biffduncan/opt/NOCduncan/website/', '/var/www/nocduncan/website', '/var/www/nocduncan', ] for path in paths: if path not in sys.path: sys.path.append(path) os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'website.settings.prod') # Activate your virtual env activate_env=os.path.expanduser('/home/biffduncan/.virtualenvs/nocduncanenv/bin/activate_this.py') exec(open(activate_env).read()) application = get_wsgi_application() prod.py from website.settings.base import * WSGI_APPLICATION = 'prod_wsgi.application' Apache config <VirtualHost *:80> #My site Name ServerName noc.biffduncan.com #Demon process for multiple virtual hosts WSGIDaemonProcess noc.biffduncan.com threads=5 #Pointing wsgi script to config file WSGIScriptAlias / /var/www/nocduncan/prod_wsgi.py WSGIProcessGroup noc.biffduncan.com #Your static files location Alias /static/ "/var/www/nocduncan/website/static" <Location "/static/"> Options -Indexes </Location> </VirtualHost> -
DateField doesn't take date.today as default
Python version 2.7 Django version 1.11 Trying to make my first Django app saving documents, here the part of models.py class Docs(models.Model): FacilityRef = models.ForeignKey(Facility) Date = models.DateField(default=date.today) Type = models.CharField(max_length=50) Link = models.FileField(upload_to='Docs/%Y/%m/%d') When making migration got the following error: Date = models.DateField(default=date.today) NameError: name 'date' is not defined Part of views.py: from django.http import HttpResponse import datetime Part of models.py from django.db import models import datetime Tried to insert the following strings in views.py and models.py as it mentioned in here and here it didn't help from django.utils import timezone from datetime import datetime What kind of import should I do to make this function work? -
Pass a Variable from Javascript to Django
I am try to create an application using javascript and python django module. So far, I have been able to make some progress. The html pages are all set and the django server configuration is working as expected. To give you some background the application has a series of workflows that user creates in the dropzone (using calculations defined in the drag zone). So lets say the user selects Multipy Divide and Subtract in the drop zone the system should store the sequence, I am able to add "Multiply,Divide,Subtract" (var_name flow_sequence where I pulled this property) as a value in the dropzone class. The application has a "Save" button as well. On the click of the Save button the value of the dropzone class should be passed (in this case "Multiply, Divide,Subtract") to the database defined in the django (flow_sequence table). So, in order to achieve that I need to first pull the value from the HTML page (javascript variable) to the django views and then pass it to the database to save it as following Flow_sequence|Time_stamp "Multiply, Divide,Subtract" | 2:25 AM IST Please suggest on how to approach the following. Pass the variable flow_sequence to the django views. Retrieve … -
custom urls and views in oscar
I can't seem to get the urls to match in oscar. My oscar app is a subapp in my main app. My understanding is to create views and urls in the app.py in the sub modules in oscar.It keeps throwing NoReverseMatch. Oscar pages all loads, just not my custom views in myapp/shop/dashboard/app.py from django.contrib.auth import views as auth_views from django.contrib.auth.forms import AuthenticationForm from django.conf.urls import include, url from oscar.core.application import DashboardApplication from oscar.core.loading import get_class from views import HomeViews class DashboardApplication(DashboardApplication): def get_urls(self): urls = [ url(r'^someurl/', HomeViews.dosomething, name="hi"), ] return self.post_process_urls(urls) application = DashboardApplication() in myapp/shop/dashboard/views.py from django.conf import settings from django.db.models import User from oscar.app.partner.models import Partner from django.middleware.csrf import get_token from oscar.apps.dashboard.views import HomeView as CoreHomeView class HomeView(CoreHomeView): def dosomething(request): return HttpResponse("hello") in my main app, I registered the shop in my settings.py INSTALLED_APPS =[ ... ]] + get_core_apps(['shop']) and in my main app url I have included oscar urls from shop.app import application as shop_app urlpatterns = i18n_patterns( url(r'^shop/', include(shop_app.urls)), -
How to combine two Querysets into one from different models?
I need to combine two Querysets from different models into one. The most suggested solutions I've found online are: To use | and &, but this works only in querysets from the same model To use chain and list, but this takes away some of the queryset methods, and because of the way the code in my project is structured I cannot change that. I tried it and didn't work. I read about Q, but it's not clear to me how I can apply it to accomplish what I need. Basically I need to combine two querysets from different models into a third queryset, not a list. They share some fields names, perhaps that's useful with Q. In example: queryset_1 = Cars.objects.all().filter(color='red') queryset_2 = Horses.objects.all() queryset_3 = queryset_1 + queryset_2 queryset_3.order_by('date') -
Django (audio) html error
I have this project with django, everything working fine. But when I go to a page where songs will be showen, and also the user have the option to play the songs, I get an error even if everything is working fine. In the html page, when I remove the audio option " <'audio'>...<'/audio'> I get no errors, but once I get it back, the error back with it, so the problem is with the <'audio'> tag I guess The view : @login_required() def songs(request, filter_by=None): song_ids = [] for album in Album.objects.filter(user=request.user): for song in album.song_set.all(): song_ids.append(song.pk) users_songs = Song.objects.filter(pk__in=song_ids) if filter_by == 'favorites': users_songs = users_songs.filter(is_favorite=True) return render(request, 'music/songs.html', { 'song_list': users_songs, 'filter_by': filter_by, }) the bit of code of html page: <td> <audio controls controlsList="nodownload"> Your browser does not support the <code>audio</code> element. <source src="{{ song.audio_file.url }}" type="audio/wav"> </audio> </td> and this is the error : Traceback (most recent call last): File "C:\Users\elmou\AppData\Local\Programs\Python\Python36-32\lib\wsgiref\handlers.py", line 141, in run self.handle_error() File "C:\Users\elmou\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\servers\basehttp.py", line 88, in handle_error super(ServerHandler, self).handle_error() File "C:\Users\elmou\AppData\Local\Programs\Python\Python36-32\lib\wsgiref\handlers.py", line 368, in handle_error self.finish_response() File "C:\Users\elmou\AppData\Local\Programs\Python\Python36-32\lib\wsgiref\handlers.py", line 180, in finish_response self.write(data) File "C:\Users\elmou\AppData\Local\Programs\Python\Python36-32\lib\wsgiref\handlers.py", line 274, in write self.send_headers() File "C:\Users\elmou\AppData\Local\Programs\Python\Python36-32\lib\wsgiref\handlers.py", line 331, in send_headers if not self.origin_server or … -
Filter Django Form ModelMultipleChoiceField Query-set by Model Foreign-key
I am creating an unordered list with a form's ModelMultipleChoiceField where I assign all 'Country' Models to the form fields queryset parameter. I also have another ModelMultipleChoiceField on the form that represents another model 'CountryRegion' which has a foreign key back to the 'Country' model. When hovering over one of the list items, another unordered list will appear next to the list item with all the regions queried by the form's region MultipleChoiceField. Right now it shows all the regions in my database for every list item, 1 list item for each country, that I hover over. Since the region unordered list is nested in the country unordered list, is it somehow possible to pass the currently hovered country in as a parameter to "form.region.field.choices" to only get regions for that country ? HTML <ul class="categories_children hidden-drilldown"> {% for value, text in form.country.field.choices %} <li class="sub-item country" data-expid="{{ value }}"> <label class="mentor-preference-choice"> <input name="country" type="checkbox" value="{{ value }}"> {{ text }} <a class="menu-arrow country-arrow"></a> </label> <ul class="categories_children hidden-drilldown"> {% for value, text in form.region.field.choices %} <li class="sub-item country" data-expid="{{ value }}"> <label class="mentor-preference-choice"> <input name="country" type="checkbox" value="{{ value }}"> {{ text }} <a class="menu-arrow country-arrow"></a> </label> </li> {% endfor %} … -
What's the best way to connect these two Django models
In a Django project I have a Companies model and am putting together a ClinicalTrials model (CT), both of which are stored in a SQlite3 database for now. My initial plan was to query the CT.gov API for a company_name when a user visits the company page and store the results in the CT model mapping the company's primary key from the Companies model to a Foreign Key in the CT model. As I start working through it though, I've realized that a trial will have a lead and could have multiple Collaborators which would result in storing multiple copies of the same trial record. So, I want to write the trial record once once and then connect multiple companies to the record. My problem arises when I try to connect the other companies to the trial, simple because the company names in the trail are not always an exact match in my Companies model (i.e. my Companies table has the company_name as "Pharma Company Inc." and the collaborator field is "Pharma Company"). Is it best to search the Companies model using regex? Is there a better solution? Also, what's the best way to store multiple Foreign Keys in a … -
Django Rest Framework - Override serializer create method for model with self-referential M2M field
I have a model that looks like this: class Profile(models.Model): following = models.ManyToManyField('Profile', related_name='followed') admin_notes = models.TextField() And a Django Rest Framework serializer that looks like this: class ProfileSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Profile fields = '__all__' When creating a new Profile I want to interrupt the save/create to set admin_notes programmatically. I know how do to this inside a function-based view, but I am using DRF's viewsets this time and so I want to do this inside the serializer. The self-referential relationship is giving me trouble, though. I tried this within the ProfileSerializer: def create(self, **validated_data): p = Profile(**validated_data) p.admin_notes = 'Test' p.save() This, as well as trying Profile.objects.create instead of just making a new Profile instance in the first line, resulted in the following error: Exception Value: "<Profile>" needs to have a value for field "id" before this many-to-many relationship can be used. Trying this: def create(self, validated_data): validated_data['admin_notes'] = 'Test' return super(ProfileSerializer, self).create(**validated_data) Results in this error: Exception Value: create() got an unexpected keyword argument 'following' I understand that Django creates m2m relationships in a two-step-save process, so the error makes sense but still leaves me stumped as to how I can move forward. How can I … -
Using Django to send Gmail
This is very much potentially a duplicate question, but none of the other obvious duplicates have resolved the issue for me: This is an inherited project. My settings.py includes: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'my_username@gmail.com' EMAIL_HOST_PASSWORD = 'my_password' EMAIL_PORT = '587' EMAIL_USE_TLS = True DEFAULT_FROM_EMAIL = 'my_username@gmail.com' DEFAULT_FEEDBACK_EMAIL = 'my_username@gmail.com' SERVER_EMAIL = 'my_username@gmail.com' ACCOUNT_EMAIL_VERIFICATION = 'none' The code that I'm trying to run is: subject = 'Subject' template = get_template('accounts/email-templates/email-activation.html').render(Context(ctx)) email = EmailMessage(subject, template, to=[send_to]) email.content_subtype = "html" try: email.send() My error when trying repeatedly with python manage.py shell is: gaierror: [Errno 8] nodename nor servname provided, or not known My dns seems fine, sudo killall -HUP mDNSResponder and dscacheutil -flushcache have been run without success, but I'm hardly an expert on dns settings. My hosts file is: 127.0.0.1 localhost 255.255.255.255 broadcasthost ::1 localhost Advice appreciated! -
Running cookiecutter django on an intranet
Now that Caddy has been adopted which comes by default setup for https and requires the domain name to be routable from the internet. What is the proper setup to run on an intranet with only http without access from the internet? -
Is well this way to implement seo in django?
I'm building a site in which SEO it's a very important requisite. I'm using django, so, I put my way of doing SEO here because I dont know if it is well, or if there is a better way to do it. First, let's go with a model. I'm writting the meta attributes in every model that require to be SEO friendly, generally I use model inheritance with an abstract model with this fields: meta_keywords and meta_description. But for the sake of brevety, I'll just show you an example with a simple model. class Product(models.Model): ... name = models.CharField(max_length=255, unique=True) meta_keywords = models.CharField(max_length=255, help_text='Comma delimited set of SEO keywords for meta tag') meta_description = models.CharField(max_length=255, help_text='Content for description meta tag') Also in settings.py I wrote a code for generally keywords and description, as well the site's name SITE_NAME = 'my site name here' META_KEYWORDS = 'general, keywords, separate, by, comma, here' META_DESCRIPTION = 'General description of the site here' To make this info available to all pages, I used a django context processor def meta_context_processor(request): return {'site_name': settings.SITE_NAME, 'meta_keywords': settings.META_KEYWORDS, 'meta_description': settings.META_DESCRIPTION,} With this I have defaults values to use when a view doesn't set them. Now I use them …