Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django extra registration details not saving
I have form.py with class RegistrationForm and everything works fine but the extra details like email, first and last name, roles is not saved to my account/User profiles but first and last name + emails is saved under AUTHENTICATION AND AUTHORIZATION/Users I been trying to figure our if I made some mix up with model, form or views. What could be the problem? Using python 3 with latest django 2nd 3rd -
Djnago function to return a link
How can I write the same function using python 2.7, instead of python 3 . def order_pdf(obj): return '<a href="{}">PDF</a>'.format( reverse('orders:admin_order_pdf', args=[obj.id])) order_pdf.allow_tags = True order_pdf.short_description = 'PDF invoice' -
How to setup a asyncio tcp server in Django with uwsgi
1.I installed the lastest greenlet and uwsgi with aysncio support. 2.Create a new Django project and write a tcp server with asyncio. class TcpServer(asyncio.Protocol): def connection_made(self, transport): ..... def data_received(self, data): ..... def start_tcp_server(): host = '127.0.0.1' port = 7000 #uvloop doesn't support Windows if platform.platform().find('Windows') != -1: loop = asyncio.get_event_loop_policy().new_event_loop() else: import uvloop loop = uvloop.new_event_loop() asyncio.set_event_loop(loop) coro = loop.create_server(TcpServer, host, port) server = loop.run_until_complete(coro) p('serving on {}'.format(server.sockets[0].getsockname())) try: loop.run_forever() except Exception as e: print(traceback.format_exc()) print"server exit") finally: server.close() loop.run_until_complete(server.wait_closed()) loop.close() def TcpServerThread(): try: print('TcpServerThread called') server = threading.Thread(target=start_tcp_server) server.setDaemon(True) server.start() except Exception as e: print(traceback.format_exc()) print('start tcp server error') create some views in project. call TcpServerThread() in wsgi.py import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "Charger.settings") application = get_wsgi_application() from ipc.tcpserver.TcpServer import TcpServerThread TcpServerThread() I start uwsgi with asyncio options. uwsgi --asyncio 512 -x /path/to/project/uwsgi_cfg.xml 127.0.0.1:9000 1024 true /tmp/xxx.pid 2 xxx.wsgi /path/to/project/ true true true true /var/log/uwsgi/xxx.log 6048 After I start the uwsgi, it seems that it can't serve any other HTTP requests. How to fix it? -
Location widget in messenger platform displays a search bar in mobile version but not in Desktop Version
Facebook Desktop widget I don't get a search bar when opening messenger in browser version. When I inspect and check the console it shows an error : ErrorUtils caught an error: "navigator.permissions.query(...).then(...).done is not a function". Subsequent errors won't be logged; see https://fburl.com/debugjs. ja @ qtaMy7UNoCv.js:47. I am using python/django to integrate with messenger platform -
How to List and Delete in memcache python
I set the cache values from my code. i need to get defined data list and delete defined data from terminal. i googled. but i could not solve it. This memcache for my python django project. import memcache client = memcache.Client([('127.0.0.1', 11211)]) data = {"some_key1": "value1","some_key2": "value2",} client.set_multi(data, time=15, key_prefix="pfx_") print "saved the dict with prefix pfx_" print "getting one key: %s" % client.get("pfx_some_key2") print "Getting all values: %s" % client.get_multi(["some_key1", "some_key2"], key_prefix="pfx_") it is my code -
apache2: /etc/apache2/sites-available is missing on macos
I am trying to configure apache2 so that it communicates with django and I am unable to the 'sites-available' directory where I believe a 'defaults' directory should reside. The following is my file structure under the 'etc/apache2/' directory: ├── extra │ ├── httpd-autoindex.conf │ ├── httpd-dav.conf │ ├── httpd-default.conf │ ├── httpd-info.conf │ ├── httpd-languages.conf │ ├── httpd-manual.conf │ ├── httpd-mpm.conf │ ├── httpd-multilang-errordoc.conf │ ├── httpd-ssl.conf │ ├── httpd-userdir.conf │ ├── httpd-vhosts.conf │ └── proxy-html.conf ├── httpd.conf ├── httpd.conf.bak ├── httpd.conf.pre-update ├── magic ├── mime.types ├── original │ ├── extra │ │ ├── httpd-autoindex.conf │ │ ├── httpd-dav.conf │ │ ├── httpd-default.conf │ │ ├── httpd-info.conf │ │ ├── httpd-languages.conf │ │ ├── httpd-manual.conf │ │ ├── httpd-mpm.conf │ │ ├── httpd-multilang-errordoc.conf │ │ ├── httpd-ssl.conf │ │ ├── httpd-userdir.conf │ │ ├── httpd-vhosts.conf │ │ └── proxy-html.conf │ └── httpd.conf ├── other │ └── php5.conf └── users ├── Guest.conf ├── aphexlog.conf └── secops.conf If anyone knows if there is a possibility of a alternative config file with the same properties or some other solution... maybe I am just being dumb but everything that I have found online indicates that I should have this properties file. Any and all … -
How to update a foreign key field in Django models.py?
Here is the source: https://docs.djangoproject.com/en/1.8/topics/db/queries/ At the beginning, let's look at the models.py field: from django.db import models class Blog(models.Model): name = models.CharField(max_length=100) tagline = models.TextField() def __str__(self): # __unicode__ on Python 2 return self.name class Author(models.Model): name = models.CharField(max_length=50) email = models.EmailField() def __str__(self): # __unicode__ on Python 2 return self.name class Entry(models.Model): blog = models.ForeignKey(Blog) headline = models.CharField(max_length=255) body_text = models.TextField() pub_date = models.DateField() mod_date = models.DateField() authors = models.ManyToManyField(Author) n_comments = models.IntegerField() n_pingbacks = models.IntegerField() rating = models.IntegerField() def __str__(self): # __unicode__ on Python 2 return self.headline This is how, a row or an object is created of Blog type: >>> from blog.models import Blog >>> b = Blog(name='Beatles Blog', tagline='All the latest Beatles news.') >>> b.save() My question is how to update blog column/attribute of Entry object (which stores Foreign Key in relation to Blog) with the entry I created in Blog class? -
Can I change the Exception's message language to other language?
Can I change the Exception's message language to Chinese? try: new_project = admin_conn.conn.identity.create_project(**project_params) # create_project print (new_project, new_project.id, "new project created") except Exception as e: print (e.message) render(request, '/register/', {"errors": e.message.encode('utf-8')}) The e.message.encode('utf-8') is english, how can change it to Chinese? -
local server error in divio app installation django-cms
I am trying to install DIVIO app , and when I try to set it up this is the error New version 3.3.2 is available. Type divio version to show information about upgrading. Usage: divio project setup [OPTIONS] SLUG Error: Invalid value for "-p" / "--path": Path "." is not writable... I am running windows 7 and docker terminal is already running -
Signal post_save in Django and models
I have function with signal: @receiver(post_save, sender=Task) def my_handler(): executor = User.objects.filter(user_type='Executer') executor.balance += Task.money executor.save() My function should add money to executor after task added. But it gives mistake like: Internal Server Error: /api/v1/tasks/ Traceback (most recent call last): ... File "/home/k/pro/freelance-django/free/lib/python3.5/site-packages/django/db/models/fields/__init__.py", line 1853, in get_prep_value return int(value) ValueError: invalid literal for int() with base 10: 'Executer' [20/Sep/2017 14:00:30] "POST /api/v1/tasks/ HTTP/1.1" 500 188088 User class looks like: class User(AbstractUser): CUSTOMER = 1 EXECUTER = 2 USER_TYPES = ((CUSTOMER, ('Customer')), (EXECUTER, ('Executer')),) user_type = models.IntegerField(choices=USER_TYPES, default=EXECUTER, verbose_name='Тип пользователя') balance = models.DecimalField(decimal_places=2, max_digits=7, default=0, verbose_name='Баланс') How should I make it work? -
AssertionError: datetime.datetime(2017, 9, 20, 4, 43, 24, 206775, tzinfo=<UTC>) != '2017-09-19 08:47:51.807533'
I run tests.py for tests, so I got an error self.assertEqual(self.user1.regist_date, '2017-09-19 08:47:51.807533') AssertionError: datetime.datetime(2017, 9, 20, 4, 43, 24, 206775, tzinfo=<UTC>) != '2017-09-19 08:47:51.807533' I wrote in tests.py like #coding:utf-8 from django.test import TestCase from app.models import User # Create your tests here. class UserModelTests(TestCase): def setUp(self): self.user1 = User.objects.create(name='Tom', regist_date = '2017-09-19 08:47:51.807533',age=20) def test_user1_name(self): self.assertEqual(self.user1.name, 'Tom') def test_user1_regist_date(self): self.assertEqual(self.user1.regist_date, '2017-09-19 08:47:51.807533') def test_user1_age(self): self.assertEqual(self.user1.age, 20) models.py is class User(models.Model): name = models.CharField(max_length=200,null=True) regist_date = models.DateTimeField(auto_now=True) age = models.IntegerField(max_length=10,null=True) I thought type of regist_date is datetime.datetime not string, so I rewrote setUp of tests.py is self.user1 = User.objects.create(name='Tom', regist_date = datetime.datetime(2017, 9, 20, 4, 43, 24, 206775, tzinfo=<UTC>),age=20),so Can't assign to function call error happens.What is wrong in y method?How can I fix this? -
Sanity and validation of a raw html form created in django template
I have an Attendance model which basically stores attendance status of an employee of a department for a date. A supervisor marks the attendance of all the employees of a department for a date in one go. So to allow this, I render a list of all the employees of a department in a table and for each of them have a checkbox which represents Present/Absent status and a textbox that stores reason for absence. As I figured out there are 2 ways to do this : Formset Raw html forms in template with manually writing input elements. I implemented the functionality using the 2nd option (since I didn't have much control over the layout while using Formset) in which : I use request.POST.get('date') to get the date user inputs then request.POST.getlist('employees[]') to access the user ids of employees being selected and only for these employees I access the value entered in Reason text box using request.POST.get(''). It works fine mostly. But I have a few questions about this approach : Given that all user input is evil, is this a secure way since I am accessing raw input text data user entered using the request.POST dictionary. How do I … -
Create HTML table from python list using django framework
I have a file handling python script which populates a list a dictionaries. After I obtain this data, I want to create an html table to display the data using the django framework (I have never used django earlier). Is it possible to pass the list variable to the html file without creating additional .py files? Also how do I create a loop to iterate through all the dictionaries of the list? -
DRF APITestCase not use `multipart` with other param
I have 2 models. First is House. Second is HouseImage Therefore I have to submit the image with ForeigneKey I can upload by using the REST normally, but failed to do unittest. The reason why I keep doint unittest in here because I have a more specifications waiting for me and I would not do hand-test for sure. django==1.11.5 djangorestframework==3.6.4 python3.6.2 PostgreSQL 9.6.5 on x86_64-apple-darwin14.5.0, compiled by Apple LLVM version 7.0.0 (clang-700.1.76), 64-bit import tempfile from PIL import Image from django.contrib.auth.models import User from model_mommy import mommy from rest_framework import status from rest_framework.reverse import reverse from rest_framework.test import APITestCase, APIClient from soken_web.apps.houses.models import House class HouseImageTest(APITestCase): def setUp(self): self.client = APIClient() self.user = mommy.make(User, username='Pan') self.house = mommy.make(House, location="100.00, 100.00") def test_post_image(self): self.client.force_authenticate(user=self.user) image = Image.new('RGB', (100, 100)) tmp_file = tempfile.NamedTemporaryFile(suffix='.jpg') image.save(tmp_file) data = { 'image': tmp_file, 'house': self.house.id, } response = self.client.post(reverse('api:house_images-list'), data, format='multipart') self.assertEqual(status.HTTP_201_CREATED, response.status_code) Problem: Server raises appliation/json type to me Attempts: 1. Replace format=multipart with content_type/multipart'. Same error 1. User bothformat=mulipartandcontent_type/multipart`. It is not permitted by DRF References: How can I test binary file uploading with django-rest-framework's test client? http://www.django-rest-framework.org/api-guide/testing/ -
GeoDjango could not find GDAL library in Windows 10
I am using Djago 11.4 on Windows 10. I followed GeoDjango's installation instructions https://docs.djangoproject.com/en/1.11/ref/contrib/gis/install/ but I am still having problems when I try and migrate my models. I receive this error: django.core.exceptions.ImproperlyConfigured: Could not find the GDAL library (tried "gdal201", "gdal20", "gdal111", "gdal110", "gdal19") Everything I have found on this error says to change the system environment variables. I installed OSGe4W and added GDAL_DATA = C:\OSGeo4W\share\gdal as well as PROJ_LIB= C:\OSGeo4W\share\proj. I am not sure what else to try and I would appreciate any more insight. -
Django - url is not matching any patter when being redirected
I am working on a django project and I have a html web page and from the web page I want to pass in an Id and through that id, update a record. I have the url setup and the html page url redirect. I am passing what is needed in the url, but i am getting a pattern matching error. I tried everything and for some reason it is not working. does anyone know what is oging on or can help me figure out what is causing this error. I will attach all the info below: Here is the url link: url(r'^(?P<source_id>[\w+][0-9]+)/default_source/$', views.setDefaultSource, name='default_source'), Here is the html file: <p>{{account.user.username}}, {{ account.source_name }}, {{ account.source_id }}, {{ account.status }} <a href="{% url 'default_source' account.source_id %}">Make Default</a> Here is the views.py : def setDefaultSource(request, source_id): currentUser = loggedInUser(request) currentSource = Dwolla.object.get(source_id = source_id) update_source = currentSource update_source.status = 2 update_source.save() return redirect('home_page') Here is the error that I am getting: NoReverseMatch at /linked_accounts/ Reverse for 'default_source' with arguments '('https://api-sandbox.dwolla.com/funding-sources/3021030d-0175-41f1-8bce-4625b8eae0fc',)' not found. 1 pattern(s) tried: ['(?P<source_id>[\\w+][0-9]+)/default_source/$'] -
How to Import Another Python 3 File in Django Settings.py?
I'm using Python 3. I have two Python files in the same directory: first.py and second.py. In the beginning of first.py, I use: from second import * However, it returns the following error message: ModuleNotFoundError: No module named 'second' How should I import it in first.py? Update: To clarify my specific use-case, I am trying to split my settings.py in Django. I have a main settings.py file and another one that only includes the confidential information. I followed this following documentation that uses the following line in settings.py: from settings_local import * Note that settings_local.py is in the same directory. However, it returns the following error message: ModuleNotFoundError: No module named 'settings_local' I know the document says "Some of the examples listed below need to be modified for compatibility with Django 1.4 and later." but I do not know how to use it in Python 3. -
Django update only blank rows in model instance
I'm looping through a list of dicts and creating models (journals) from dicts. They have a many to many relationship with Researcher. Each dict looks like this {'abbreviation': 'Front. Artif. Intell. Appl.', 'journal_type': 'k', 'title': 'Frontiers in Artificial Intelligence and Applications'} However, there are duplicates in this list, which is fine, I check manually to see if they exist, if they do, I dont create a new model for it. BUT. The problem is, the entries in the list of dicts has duplicates with varying degrees of missing columns. Eg, Entry 123 {'abbreviation': 'Front. Artif. Intell. Appl.', 'journal_type': 'k', 'title': 'Frontiers in Artificial Intelligence and Applications'} Entry 124 {'abbreviation': 'Front. Artif. Intell. Appl.', 'issn':123 'journal_type': 'k', 'title': 'Frontiers in Artificial Intelligence and Applications'} As you can see, 124 is more 'complete' than 123. At the point of 123, I've already created the journal object from that hash. However, I want to update the same row with only the new fields from 124 (in this case, update the row with the issn) What is the proper way to do this? :) -
Ubuntu 16.04 Django 1.11.5 virtualenv opencv
I'm new to Ubuntu and also fairly new to web development, so I am hoping there is some obvious thing I am missing. My problem is as follows, I have a box running Ubuntu 16.04 I have my Django project with a virtualenv I used (with the virtualenv activated) pip install opencv-python, and it seemed to work all the files seem to be where I would think they need to be (env/lib/python3.5/site-packages/{cv2,numpy}). BUT when I run a manage.py command I get an error in the init.py (so it is finding the opencv package) of "ImportError: libSM.so.6: cannot open shared object file: No such file or directory". I get the same error when I enter python in the virtualenv and try to import cv2. You can see the error here Is .cv2 in the error a namespace? Is there an way I can get more information or do a python search for the namespace? -
Cannot run Django unit test. Returns django.core.exceptions.ImproperlyConfigured
I've been running unit tests (test.py) on my Django app for ages with no trouble. In my last session I was tinkering with my MYSQL database and models. I have been dropping and recreating the DB, deleting the migrations file and making migrations from scratch while I experiment with the models. Now, the unittests won't run. Traceback (most recent call last): File "/opt/pycharm-2017.2.1/helpers/pycharm/_jb_unittest_runner.py", line 35, in <module> main(argv=args, module=None, testRunner=unittestpy.TeamcityTestRunner, buffer=not JB_DISABLE_BUFFERING) File "/usr/lib/python3.5/unittest/main.py", line 93, in __init__ self.parseArgs(argv) File "/usr/lib/python3.5/unittest/main.py", line 140, in parseArgs self.createTests() File "/usr/lib/python3.5/unittest/main.py", line 147, in createTests self.module) File "/usr/lib/python3.5/unittest/loader.py", line 219, in loadTestsFromNames suites = [self.loadTestsFromName(name, module) for name in names] File "/usr/lib/python3.5/unittest/loader.py", line 219, in <listcomp> suites = [self.loadTestsFromName(name, module) for name in names] File "/usr/lib/python3.5/unittest/loader.py", line 153, in loadTestsFromName module = __import__(module_name) File "/home/danny/PycharmProjects/AskArby/deals/tests.py", line 3, in <module> from deals.models import Retailer File "/home/danny/PycharmProjects/AskArby/deals/models.py", line 5, in <module> class Retailer(models.Model): File "/home/danny/PycharmProjects/AskArby/deals/models.py", line 6, in Retailer name = models.CharField(max_length=200) File "/home/danny/.virtualenvs/AskArby/lib/python3.5/site-packages/django/db/models/fields/__init__.py", line 1061, in __init__ super(CharField, self).__init__(*args, **kwargs) File "/home/danny/.virtualenvs/AskArby/lib/python3.5/site-packages/django/db/models/fields/__init__.py", line 172, in __init__ self.db_tablespace = db_tablespace or settings.DEFAULT_INDEX_TABLESPACE File "/home/danny/.virtualenvs/AskArby/lib/python3.5/site-packages/django/conf/__init__.py", line 56, in __getattr__ self._setup(name) File "/home/danny/.virtualenvs/AskArby/lib/python3.5/site-packages/django/conf/__init__.py", line 39, in _setup % (desc, ENVIRONMENT_VARIABLE)) django.core.exceptions.ImproperlyConfigured: Requested setting DEFAULT_INDEX_TABLESPACE, but settings are … -
How to start a django project on cloud9?
I just created a django workspace in cloud9. It gives me an empty folder with the project name with nothing on it. What commands do I need to type to start a django project and get coding. -
No migrations to apply. I got this error in test
I got an error when I do test, Operations to perform: Apply all migrations: admin, app, auth, contenttypes, sessions Running migrations: No migrations to apply. I wrote in test.py class UserModelTests(TestCase): def test_is_empty(self): queryset = User.objects.order_by('user_id').values()[:2] expected = [ {'name': 'Tom', 'user_id': 1, 'nationarity': 'America', 'dormitory': 'A', 'group': 3} ] for idx, item in enumerate(expected): self.assertDictEqual(item, queryset[idx]) I read documents and other web site, I found fixtures & setUp() are needed maybe, but I cannot understand how to write it.How should I fix this?What should I add to this code? -
Django not serving webpack
My application structure looks like - MyProject -- MyProject/ -- assets/ -- bundles/ # this is where the bundles get outputted -- js/ -- node_modules -- templates -- webpack-stats.json -- webpack.config.js All relevant code concerning webpack on the django side: INSTALLED_APPS = [ ... 'webpack_loader', ] WEBPACK_LOADER = { 'DEFAULT': { 'BUNDLE_DIR_NAME': 'bundles/', 'STATS_FILE': os.path.join(BASE_DIR, 'webpack-stats.json'), } } ... STATIC_URL = '/static/' STATICFILES_DIR = [ os.path.join(BASE_DIR, 'assets') ] My url file looks like this from django.conf.urls import url from django.contrib import admin import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', views.index), ] on the webpack side: var path = require("path") var webpack = require('webpack') var BundleTracker = require('webpack-bundle-tracker') module.exports = { context: __dirname, entry: './assets/js/index', output: { path: path.resolve('./assets/bundles/'), filename: "[name]-[hash].js", }, plugins: [ new BundleTracker({filename: './webpack-stats.json'}), ], module: { loaders: [ { test: /\.js$/, loader: 'babel-loader', exclude: /node_modules/ }, { test: /\.jsx$/, loader: 'babel-loader', exclude: /node_modules/ } ] } } My template file looks like this {% load render_bundle from webpack_loader %} <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Example</title> </head> <body> <div id="react-app"></div> {% render_bundle 'main' %} </body> </html> When I run python manage.py runserver, my html file gets sent back to me on localhost:8000 but the javascript file … -
Django-autocomplete-light & QuerySetSequence - getting the name of the original model for each QuerySequenceModel
I have 3 models from cities_light: City, Region and Country. I'm using QuerySetSequence with Django-autocomplete to create a queryset involving all 3 of these models, so that a user can type in one search bar to search for all types of location. I have things working but my current implementation feels very hacky, so I'm looking to see if there's a better way of doing this. As far as I can tell, while QuerySequenceModel inherits all the attributes of the relevant model (in this case, either City, Region or Country), it doesn't have an attribute that simply returns the name of the model it's inheriting from. So, the only way I can see of actually determining which model a QuerySequenceModel is to rather naively check to see whether it contains any defining attributes that uniquely identify it as either a City, Region or Country. Thus: for queryset in locations.query._querysets: if not hasattr(queryset.model, 'country'): profile.favourite_countries = queryset elif hasattr(queryset.model, 'region'): profile.favourite_cities = queryset elif hasattr(queryset.model, 'country'): profile.favourite_regions = queryset This works, but is hardly elegant, and also needs additional hacking in order to be fully functional (i.e. recognizing when one location type isn't present). For reference, here is the full list … -
How do I create and submit a form from a model inside a modal?
In my app I needed to add a form created from a model so I can add and edit records in my database. I did it in the following way to render the form in a separate page.: 1) I created a forms.py file: from django import forms from store_app.models import Product class AddNewProductForm(forms.ModelForm): class Meta: model = Product fields = ["title", "description", "weight", "price"] # Fields from my model class EditProductForm(forms.ModelForm): class Meta: model = Product fields = ["title", "description", "weight", "price"] # Fields from my model 2) Then I created the html template to display the form, edit_product.html: {% extends "store_app/base.html" %} {% load static %} {% block title %}Edit Product{% endblock %} {% block content %} <h1>Edit Product</h1> <form method="POST"> {{ form.as_p }} {% csrf_token %} <input type="submit" class="btn btn-primary" value="Submit!"> </form> {% endblock %} 3) After that, I added the following to my app's views.py: from store_app.models import Product from store_app.forms import EditProductForm from django.shortcuts import render, get_object_or_404 def index(request): return render(request, 'simple_app/main.html') def edit_product_view(request, id): instance = get_object_or_404(Product, id=id) form = EditProductForm(instance=instance) if request.method == "POST": print("POST") form = EditProductForm(request.POST, instance=instance) if form.is_valid(): form.save(commit=True) return index(request) else: print("ERROR FORM INVALID") return render(request, 'simple_app/edit_product.html', {'form': form}) …