Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django modelformset_factory: Re-initialization not working
I have a model called Location to which I want to assign a couple of images. I try to solve this with a many-to-one relationship and use simple ModelForms and modelformset_factory to be able to save a location and it's images in one simple form. This is per se working just fine. But the modelformset seems to keep the values of images I saved and just adds another bunch of inline forms on top. How can I prevent this behaviour. my location create view looks like this: def location_create(request): ImageFormSet = modelformset_factory(Image, form=ImageForm, extra=2) if not request.user.is_authenticated: if not request.user.is_staff or not request.user.is_superuser: raise Http404 raise PermissionDenied if request.method == 'POST': form = LocationForm(request.POST or None, request.FILES or None) formset = ImageFormSet(request.POST, request.FILES, queryset=Image.objects.none()) if form.is_valid() and formset.is_valid(): instance = form.save(commit=False) instance.save() for image_form in formset.cleaned_data: image = image_form.get('image') photo = Image(location = instance, image=image) photo.save() messages.success(request,"Successfully created") return HttpResponseRedirect(instance.get_absolute_url()) else: form = LocationForm() formset = ImageFormSet() print("Formset: ") print(formset) if form.errors: messages.error(request,"Nope, not created") context = { "form": form, "formset": formset, } return render(request,'location_form.html', context) When I call the view for the first time the formset looks like this: <input id="id_form-TOTAL_FORMS" name="form-TOTAL_FORMS" type="hidden" value="2" /><input id="id_form-INITIAL_FORMS" name="form-INITIAL_FORMS" type="hidden" value="0" … -
What would be the most djangoish way to run through relations until last child?
I'm struggling on finding an efficient way to go through Django m2m relations. My use is case : I receive a string from a form and update the status of an element with this string. If this element has children, I update their status with the same value. If those children element have themselves children, then I update the status and goes through their children etc .. My model m2m field is like : parent = models.ManyToManyField('self', blank=True, default=None, symmetrical=False, verbose_name="") Currently I've written something like this : if model == Ensemble: children = elem.ensemble_set.all() for child in children: update_elem_statut(child, statut) for en in child.ensemble_set.all(): update_elem_statut(en, statut) if len(en.ensemble_set.all()): for en_child in en.ensemble_set.all(): update_elem_statut(en_child, statut) But that's definitely not recursive. I would need to loop through every children until there are only children element. I've no idea what would be the most pythonish/djangoish way to do this. Thanks in advance for any help. -
Django Unleashed Cp.22: FieldError: Unknown field(s) (username) specified for User
I'm following a tutorial book for Django (Django Unleashed) and I think there is a problem with the code when using newer versions of Django (i've read about problems with this chaper on amazon as well). So for future students of this book I ask this openly and in relation to the book. For the creation of a custom user model the book suggests a user model that does not have a 'username' field. This Error occursd during makemigrations: django.core.exceptions.FieldError: Unknown field(s) (username) specified for User There are other topics about this error on StackOverflow and they suggest that django.contrib.auth.admin.UserAdminneeds the 'username' specified and therefore suggest adding an attribute called add_fieldsets to a class that inherits form UserAdmin. My question (so I dont have to get ahead of the code in the book in run into other problems) ... is it possible to create a custom user profile without specifiying a username and without the admin class? Here is my code so far: User model class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField('email adress', max_length=254, unique=True) is_staff = models.BooleanField('staff status', default=False) is_active = models.BooleanField('active', default=False) name = models.CharField(max_length=255) joined = models.DateTimeField("Date Joined", auto_now_add=True) USERNAME_FIELD = 'email' objects = UserManager() def __str__(self): return … -
Installing requirements.txt
I am new to the Wagtail cms and am taking over a friend's project for his site. I have downloaded his repo and am trying to get it to run locally. I have followed the steps on the wagtail documentation http://docs.wagtail.io/en/v1.12.1/getting_started/index.html but in the site's requirements.txt file, there are some dependencies that just are not installing and giving errors: here is the output of when trying to install the requirements: build\lib.win32-2.7\psycopg2\_psycopg.pyd : fatal error LNK1120: 62 unresolved externals error: command 'C:\\Users\\Adam\\AppData\\Local\\Programs\\Common\\Microsoft\\Visual C++ for Python\\9.0\\VC\\Bin\\link.exe' failed with exit status 1120 Rolling back uninstall of psycopg2 Command "c:\python27\python.exe -u -c "import setuptools, tokenize;__file__='c:\\users\\Adam\\appdata\\local\\temp\\pip-build- bykm5e\\psycopg2\\setup.py';f=getattr(tokenize, 'open', open) (__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record c:\users\Adam\appdata\local\temp\pip- cidizd-record\install-record.txt --single-version-externally-managed -- compile" failed with error code 1 in c:\users\Adam\appdata\local\temp\pip- build-bykm5e\psycopg2\ (The full output is here: https://pastebin.com/m1ukkei8) Any help would be greatly appreciated - I am using Python 2.7 and have tried reinstalling psycopg and have installed postresql -
django request.session loses item
I have an application that posts data through ajax on the frontend. Through Django Rest Framework I accept the data in a serializer. In the serializer I set the request.session variable 'group' by doing: if test == 1: self.request.session['group'] = someValue group = self.request.session.get('group', '') So basically I do multiple post where 'test' increments so 'group' only assigns the first time. After that it just tries to get the group session variable. Later in the save method I do: self.request = self.context.get('request') The problem is that when I clear my browser cache and do some posts, the session attribute 'group' gets set succesfully the first time, but the subsequent posts result in the 'group' attribute missing from the session. (The odd thing is that the exact same routine does not always cause this problem and 'group' IS then set in the session in the subsequent posts). -
How to return CSV data from API in Django views
I am trying to retrieve a CSV dataset from an API in my Django views and then pass the dataset to the corresponding html where I want to use it to create some charts with D3. I have already implemented the charts using static example CSVs but now I want to use the 'real' data from the API. I managed to get the data from my API using this command: r = requests.post(BASE_URL + '/api/sql', data={'query-text': mysqltext, 'format': 'csv'}, auth=(token, 'not_used')) Apparently it works, because when I use the 'print' command, it shows the dataset in my terminal. However, when I do this return render(request, 'vat/nationalestimates.html', {'data': r.text}) something does not work. I used an 'alert' in the html file to see what happens with 'data', but it does not display anything, apparently 'data' is null. <script> function load() { alert('{{data}}'); } window.onload = load; </script> When I substitute 'r.text' with 'r' for example, the alert works and displays "<Response [200]>" I have already tried various things, e.g. passing the data as a JsonResponse (the result was a list of the data instead of my html on the website) but nothing seems to work for me.. This is the whole … -
Creating Django Project with Namespaces
I want to create a Project "Name wise" in django 1.8.17 I am writing on console: Django-admin startproject "Name wise" Error : No such dictionary exist. I dont know how to concatenate "Project Name" Thanks in advance. -
Writing django queries
I am new to django world and i am trying to run below sql query on django . Any clue on how to write below equivalent query in django is much appreciated . Model: class UserTraining(models.Model): Training = models.CharField(max_length = 100,unique=True) Category = models.CharField(max_length = 100) Due_date = models.DateField(default=None) def __str__ (self): return self.Training + " " + self.Category class UserSummary(models.Model): Users = models.ForeignKey(settings.AUTH_USER_MODEL) Status = models.CharField(max_length = 100) Duedate = models.DateField(default=None) CompletedDate = models.DateField(default=None) Hours = models.IntegerField(default=0) Trainings = models.ForeignKey(UserTraining,to_field='Training',blank=False,null=True) def __str__(self): return self.Status class UserProfile(models.Model): user = models.OneToOneField(User) user_category = models.CharField(max_length = 100, blank=True, null=True) mobile = models.CharField(max_length=256, blank=True, null=True) DOJ = models.DateField(default=None) def __str__(self): return self.user.first_name + " " + self.user_category Working sql Query: Select UT. Training , ifnull (US.Status ,'Pending') from SkillTracker_usertraining UT Left outer join SkillTracker_usersummary US On US.Trainings_id=UT.Training and Us.Users_id='4' where UT.Category='EMEIA' Need help in writing above sql query in django. My objective behind this is to get user training status for all of his category if he has not yet attended training it should be displayed as pending. -
Check all active users from array
I need to choose all active users with the easiest way users = [{'id': 1, 'active': False}, {'id': 2, 'active': True}, {'id': 3, 'active': True}, {'id': 4, 'active': True}, {'id': 5, 'active': True}, {'id': 6, 'active': True}] -
Django unittest m2m instance no create pk?
I am creating unittest working with M2M model. models.py from django.contrib.gis.db import models from geoposition.fields import GeopositionField from model_controller.models import AbstractModelController from soken_web.apps.customers.models import Customer class House(models.Model): ... customers = models.ManyToManyField(Customer, related_name='houses') # Use M2M in case family member do same thing First test case runs fine. But the second one it is not. tests.py import copy from django.contrib.auth.models import User from model_mommy import mommy from rest_framework.reverse import reverse from rest_framework.test import APITestCase, APIClient from soken_web.apps.customers.models import Customer from soken_web.apps.houses.models import House class HouseTest(APITestCase): def setUp(self): self.client = APIClient() self.soken_staff = mommy.make(User, username='spearhead') self.customer = mommy.make(Customer) self.data = { 'address_line_1': "testing data", 'address_line_2': "testing data", 'prefecture': "testing data", 'town': "testing data", 'city': "testing data", 'building': "testing data", 'postal_code': "10330", 'location': "13.747288, 100.528155", 'customers': self.customer.id, } def test_create_house(self): self.client.force_authenticate(user=self.soken_staff) res = self.client.post(reverse('api:house-list'), data=self.data) self.assertEqual(201, res.status_code) self.assertEqual(1, res.data.get('id')) # Confirm that mobile known ID def test_update_house(self): user = User.objects.create(username='aoc') self.client.force_authenticate(user=user) data = copy.deepcopy(self.data) data['created_user'] = self.soken_staff data['updated_user'] = self.soken_staff house = House.objects.create(**data) house.customers.add(self.customer) house.refresh_from_db() patch = { "town": "MBK", } res = self.client.patch(reverse('api:house-detail', kwargs={'pk': house.id}), data=patch) self.assertEqual(200, res.status_code) Background: In the test_update_house. I have to create the sample and then patch it. The reason why I do not use model_mommy because in … -
Django: division output from two sums
This is my current code: data = data.values('number_of_houses', 'total', 'old_price', ) return data.aggregate(number_of_houses_new=Sum('number_of_houses'), total_new=Sum('total'), house_percentage_new=Sum('number_of_houses') / Sum('total'), old_price_new=Avg('old_price', output_field=IntegerField()) ) My problem is with house_percentage_new. The value is consistently 0. How do I go about dividing two Sums? I'm using Django 1.11 and Python 3.6 -
Android Application Back-end Processing
I have only ever worked on Android applications that were primarily client-side based with some Firebase request, so I want to learn how to push processing from the client to the backend. I want to create an app that can deliver unique content to each user based on their chosen preferences (eg. Facebook Timeline). Obviously, this filtering of content should be done in the backend so what sorts of backends should I look into for completing this processing? I want to be able to implement a machine learning algorithm there to be able to find the correct results for individual users and push the content to them. -
How can I save the login session as a file in pyvmomi?
I'm Jio How can I save the login session as a file in pyvmomi? (ServiceInstance) ex) from pyVim.connect import SmartConnect si = SmartConnect(host=self.host, user=self.user, pwd=self.pwd) The problem I am having is that when I issue a command to the virtual machine, Always try to connect to vSphere is likely to cause a traffic load. So I try to save an existing session to a file and reuse it. What should I do? What better way? Thank you ! -
Django: Pass object parameters to return results in html modal view
Currently I'm using non-hardcoded urls to redirect users to a page with similar products by matching a barcode number. views.py def ItemView(request, barcode): template_name = "TESTcategories.html" products = Product.objects.filter(barcode=barcode) context = { 'products': products, } return render_to_response(template_name, context) urls.py url(r'^item/(?P<barcode>[0-9]+)$', ItemView, name='ItemView'), items.py <h3 class="product-title"><a href="{% url 'ItemView' result.object.barcode %}">{{result.object.title}}</a></h3> I'm passing the barcode arguments through based on the URL re-direct. Can I achieve a similar effect but for a 'quick view' option that will launch a pop up modal view. This is my potential modal: partials/modal.html <!-- Large Modal--> <div class="modal fade" id="modalLarge" tabindex="-1" role="dialog"> <div class="modal-dialog modal-lg" role="document"> <div class="modal-content"> <div class="modal-header"> <h4 class="modal-title">Quick Item Compare</h4> <button class="close" type="button" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button> </div> <div class="modal-body"> <!-- Product in modal --> <div class="table-responsive"> <table class="table"> {% for result in page_obj.object_list %} <thead> <tr> <th></th> <th>{{result.object.title}}</th> <th></th> <th></th> <th>£{{result.object.price}}</th> <th class="text-center"><a class="btn btn-sm btn-btn btn-success" href="{{result.object.url}}">Visit Site</a></th> </tr> </thead> {% endfor %} </table> </div> </div> <div class="modal-footer"> <button class="btn btn-primary btn-sm" type="button" data-dismiss="modal">Close</button> </div> </div> </div> </div> -
Django: filter to check if both/multiple fields are in list
I have a model ModelNameHere in Django with the fields field_a and field_b. I have a list in python with tuples of the form (a,b) I want to get all instances of the Django model where both fields are in the Python list. If there was only one field, this would be simple: my_filter_list = [a1, a2, a3] ModelNameHere.objects.filter(field_a__in=my_filter_list) But for multiple fields, this does not work my_filter_list = [(a1, b1), (a2, b2), (a3, b3)] ModelNameHere.objects.filter( ? ) Is there a way to check both fields at the same time? Alternatively, is there a way to turn my_filter_list into a temporary table so that I can join that table with ModelNameHere using both field_a and field_b as the join key? -
How to set site logo in django admin site?
I am quite new in django. I am woking on project where client wants to set favicon.ico file as site logo .How to set site logo in django admin site? I have tried with this code but does't work. {% extends "admin/base.html" %} {% load staticfiles %} {% block title %}{{ title }} | {{ site_title|default:_('Django site admin') }}{% endblock %} {% block extrahead %} <link rel="icon" href="{{STATIC_URL}}img/favicon.ico" sizes="48x48" sizes="48x48" /> {% endblock %} {% block branding %} <h1 id="site-name"><a href="{% url 'admin:index' %}">{{ site_header|default:_('Django administration') }}</a></h1> {% endblock %} -
Copy static files to volume on deployment?
How can I ensure that the most recent static files created during deployment of a Django application are copied to a volume? My web container defines a Django application that, when built, runs python manage.py collectstatic --noinput --clear. This collects all static files in the /usr/src/app/static_files directory. I'd like these static files to become available in the staticdata volume such that nginx can serve them. In other words, the contents of /usr/src/app/static_files should overwrite the contents of existing files in the staticdata volume, but not erase the contents altogether since it also contains user uploaded files. Is this possible? It feels like I am using volumes wrong for this purpose. version: '3.3' services: web: restart: always build: ./web env_file: - web-variables.env expose: - "8000" ports: - "8000:8000" volumes: - staticdata:/usr/src/app/static_files - staticdata:/usr/src/app/uploaded_files command: "./django-entrypoint.sh" depends_on: - database nginx: restart: always build: ./nginx ports: - "80:80" - "443:443" volumes: - staticdata:/data/www depends_on: - web database: image: postgres:9.2 restart: always volumes: - pgdata:/var/lib/postgresql/data ports: - "5432:5432" volumes: staticdata: pgdata: -
Repeated values in Django Query on aggregate and SUM
I am using PyGal to render some chart on the frontend. My django-view [Function Based] somewhat looks like this : if request.method == 'GET': profile = Profile.objects.get(user_profile=request.user) store_qs = Store.objects.filter(brand_admin=profile) for store in store_qs: cam_qs = Camera.objects.filter(install_location=store) for cam in cam_qs: for x in range(10, 22): value = PeopleCount.objects.filter( timestamp__date='2017-09-06', timestamp__hour=x, camera=cam).aggregate(Sum('people_count_entry'))['people_count_entry__sum'] # noqa values_list.append(value) bar_chart.add(str(cam), values_list) context = {'fun': bar_chart.render_data_uri()} return render(request, 'reports/report_daily.html', context) The issue is I am getting same values for two different camera object. Info: For instance if a store has two camera let's say cam1 and cam2. I am getting same values for both the cam which should not be the case. I don't know where I am making the mistake. Help Apprecitated Thanks in Advance :) -
best practice for documenting django templates?
I am documenting my Django project with SPHINX, following this tutorial Sphinx extracts Python docstrings from my python files to build a user readable documentation. But I wish to also document my django templates ( .html ) What are best practices to document django templates ? -
django.db.utils.IntegrityError: column "color_set_id" contains null values
app.models.py class ColorSet(models.Model): color = models.CharField(max_length=50, verbose_name='Color', default='', blank=True, null=True) code = models.CharField(max_length=50, verbose_name='Code of color', default='', blank=True, null=True) class Meta: verbose_name = 'Color' verbose_name_plural = 'Colors' Also project.models.py class Product(models.Model): title = models.CharField(max_length=200, verbose_name='Title of product') slug_field = models.SlugField(max_length=50, verbose_name='Slug', default='') description = models.TextField(verbose_name='Description') color_set = models.ForeignKey(ColorSet, verbose_name='Color', default='', blank=True, null=True) def __str__(self): return '%s %s %s' % (self.title, '->', self.category) class Meta: verbose_name = "Product" verbose_name_plural = "Products" If I am doing 'migrate', I see something like this Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/home/vladislav/.local/lib/python3.5/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line utility.execute() File "/home/vladislav/.local/lib/python3.5/site-packages/django/core/management/__init__.py", line 355, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/vladislav/.local/lib/python3.5/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/home/vladislav/.local/lib/python3.5/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/home/vladislav/.local/lib/python3.5/site-packages/django/core/management/commands/migrate.py", line 204, in handle fake_initial=fake_initial, File "/home/vladislav/.local/lib/python3.5/site-packages/django/db/migrations/executor.py", line 115, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "/home/vladislav/.local/lib/python3.5/site-packages/django/db/migrations/executor.py", line 145, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/home/vladislav/.local/lib/python3.5/site-packages/django/db/migrations/executor.py", line 244, in apply_migration state = migration.apply(state, schema_editor) File "/home/vladislav/.local/lib/python3.5/site-packages/django/db/migrations/migration.py", line 129, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "/home/vladislav/.local/lib/python3.5/site-packages/django/db/migrations/operations/fields.py", line 87, in database_forwards field, File "/home/vladislav/.local/lib/python3.5/site-packages/django/db/backends/base/schema.py", line 429, in add_field self.execute(sql, params) File "/home/vladislav/.local/lib/python3.5/site-packages/django/db/backends/base/schema.py", line 120, in execute cursor.execute(sql, params) File … -
How to escape from mysql lock
I am writing a test for my django app. In this i have override setUpclass and tearDownClass for creating a test database manually and drop the database respectively. tests.py class testcase(TestCase): @classmethod def setUpClass(cls): db=MySQLdb.connect(host=dbHost,port=dbPort,user=dbUser,passwd=dbPasswd) super(testcase, cls).setUpClass() cursor = db.cursor() query = 'CREATE DATABASE IF NOT EXISTS '+testdb+';' cursor.execute(query) cursor.close() cursor = db.cursor() query = 'USE '+testdb+';' cursor.execute(query) cursor.close() cursor = db.cursor() sql=open("empty.sql").read() cursor.execute(sql) cursor.close() db.close() views.MySQLdb=Mockdb() @classmethod def tearDownClass(cls): db = MySQLdb.connect(host=dbHost,port=dbPort,user=dbUser,passwd=dbPasswd,db=testdb) print "teardownclass" cursor=db.cursor() query = 'DROP DATABASE '+testdb+';' cursor.execute(query) cursor.close() def test_001(self): ------tests----- While running tests i encountered an Typerror in mysql query in view.py. This is not due to fault in view.py but due to some conditions in testcase. Thereafter it will execute the teardown function and the database is become hang while executing the drop database query. If i avoid the drop database query, the Type error is displayed after it occurs. I think this is because after Typerror database get locked and i can't drop it. Is my knowledge correct? How can i escape from it. I have tried sys.exc_type but it won't get in teardown function. How can i skip drop database if there is a Exception due to query executed in related … -
Google maps not showing in html
Apologies, I am really new to this - I am following the google tutorials however I am unable to get the map to show in the html. I know the javascript is executing as I can see some manual console logs I put through the script. I also know the location is taken from the user. I have 2 separate files, googlemaps.js and home.html: <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Title</title> <script src="{% static 'js/googlemaps.js' %}"></script> <script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyA9etM9rqnYas63ypURAkvEFn_W_sU0NM4&callback=initMap"> </script> </head> <body> <div id="map"> <style> #map { height: 400px; width: 100%; } </style> </div> </body> </html> And in the js file I have : var curLat = null; //user location var curLon = null; function getLocation() { if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(showPosition); } else { window.alert("no location"); } } function showPosition(position) { curLat = position.coords.latitude; curLon = position.coords.longitude; } function initMap(){ getLocation() //finds out user location to fomat the map if (curLat = null){ curLat = 42.3601; //if the user location cannot be found, set default ones curLon = -71.0589; // of boston console.log("random locations"); } var options = { zoom:10, center:{lat:curLat, lng:curLon} } var map = new google.maps.Map(document.getElementById("map"),options); } If possible, could you … -
Display flags in Django form & templates with Django-countries
I'm using Django-countries and I don't overcome to display country flags beside each country in my Django Form or in any templates. I display well the country list, I set correctly the flags folder in my static folder. But impossible to display flags. In my model I have : PaysNaissance = CountryField(blank_label='Sélectionner un pays', verbose_name='Pays de naissance') Then, my form displays countries like this : As you can see, none flags appears in my list. Do you have any idea about this issue ? Settings are well-configured, and in my template I have : <tr> <td>Pays de naissance</td> <td> <img src='{{personne.PaysNaissance.flags.url}}'/> </td> </tr> -
Change wagtail admin form fields based on user input
I've got a model called 'Block', which has multiple fields: type. This is a dropdown where you can select 3 options. URL Search Based on the type field, the URL or Search must be shown. The search field needs to preform a search using a variable: API_HOST. I've written JS to do make the form dynamic and I've extended the wagtailadmin/pages/edit.html template to inject the JS. However, I'm not sure how to pass the API_HOST (defined in dev.py) down to the template. How should I approach this situation? -
How to do locale aware sorting in Django?
In Javascript I would use the String.prototype.localeCompare() function: lst = ['Åsheim', 'Aamodt', 'Haagen', 'Hagen'] lst.sort((a, b) => a.localeCompare(b, 'nb', {caseFirst: false, numeric: true})) [ "Hagen", "Haagen", "Aamodt", "Åsheim" ] i.e. sort a and b in the nb (norwegian-bokmål) locale, ignore case (caseFirst: false) and sort numerics by value ('1' < '2' < '10'). Aside: in the nb locale, there are three extra letter at the end: ..xyzæøå and 'aa' is sorted as if it was 'å'. Based on https://docs.python.org/3.0/library/locale.html#background-details-hints-tips-and-caveats I can't use setlocale in Django (since we're running a multithreaded Apache instance). We're developing on windows so a solution using e.g. ctypes to get at glibc won't work for us. I suppose I could convert the list to json, and pass it to nodejs in a subprocess, but there has to be a better way..?