Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Run a cron job to check the due date of a task
I'm working in an integration between Django and Chatfuel. Right now the bot is almost complete, I have difficulties with the last task, I have certain tasks to do and each them have a due time, so three days before it expires I have to send a message to my client remindering him/her that he/she have to complete this task. I'm available to obtain the messenger_user_id after the first interaction with my bot, now, I know i have to run a cron job at a frequent interval to check the due date and if it's close, send a message through Broadcasting API. But I don't know how to achieve that goal. models.py class Tasks(models.Model): task = models.CharField(max_length=100) objective = models.TextField() created_date = models.DateTimeField( default=timezone.now) due_date = models.DateTimeField( default=timezone.now) def __str__(self): return self.task views.py #in here I obtain user's fb id def save_fb_id(request, username, fb_id): profile = Profile.objects.get(user__username=username) if profile.fb_id != fb_id: profile.fb_id = fb_id profile.save() return HttpResponse() -
errors while running python scripts triggered by django app
I am building a fully open source testrunner for my needs but I am running into some problems. the test runner parses a yaml file for a set of scripts in various paths and executed the scripts and uses a lib that i will be creating to return the outcome. right now i have a simple ping script that im working to get running and testing as i progress but i am getting a lot of errors. the errors are below and all the source code is also shown below the errors. The github repo for this is here. feel free to pull it in and test the issues i am seeing. https://github.com/castaway2000/testrunner The issue: I am trying to use the testrunner i built to parse a yaml file for paths to scripts i am writing for projects im using. For example if want to use a group of certain tests on a target, i can make a yaml file for each set of the types of tests. There is a certain problem I am seeing with this however, the relative path and exact path of the files are not able to use the django libraries, cause its unable to … -
Django rest framework & external api
i wanna get my data from an external API (https://example.com/consumers). Can I build my urls.py like this? url(r'^(?P<test.com/consumers)>[0-9]+)$/', views.get, name="get"), Or do you have any other(s) good idea(s) ? Thanks. -
Integrity Error: using primary_key=True
This is my Models: from django.db import models from django.contrib.auth.models import User class Bookmark(models.Model): id = models.PositiveIntegerField(primary_key=True) name = models.CharField(max_length=50) url = models.URLField() isPublic = models.BooleanField(default=True) dateTimePosted = models.DateTimeField(auto_now=True,verbose_name="posted at") user = models.ForeignKey(User, on_delete=models.CASCADE) This is my 0001_initials.py: from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='Bookmark', fields=[ ('id', models.PositiveIntegerField(primary_key=True, serialize=False)), ('name', models.CharField(max_length=50)), ('url', models.URLField()), ('isPublic', models.BooleanField(default=True)), ('dateTimePosted', models.DateTimeField(auto_now=True, verbose_name='posted at')), ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], ), ] When I am inserting values using: python manage.py shell: >>from django.contrib.auth.models import User >>user = User.objects.create_user('test', 'test@abc.com', 'test@123') >>from bookmark.models import Bookmark >>bookmark = Bookmark.objects.create(name='First Bookmark', url='example.com', user=user) this error occurs: Traceback (most recent call last): File "", line 1, in File "C:\Python34\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Python34\lib\site-packages\django\db\models\query.py", line 394, in create obj.save(force_insert=True, using=self.db) File "C:\Python34\lib\site-packages\django\db\models\base.py", line 806, in save force_update=force_update, update_fields=update_fields) File "C:\Python34\lib\site-packages\django\db\models\base.py", line 836, in save_base updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields) File "C:\Python34\lib\site-packages\django\db\models\base.py", line 922, in _save_table result = self._do_insert(cls._base_manager, using, fields, update_pk, raw) File "C:\Python34\lib\site-packages\django\db\models\base.py", line 961, in _do_insert using=using, raw=raw) File "C:\Python34\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) … -
How to fix ImproperlyConfigured in django 1.7?
ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. [2018-01-25 02:20:16 +0000] [13560] [INFO] Worker exiting (pid: 13560) Traceback (most recent call last): File "/home/web/git/myprojc/.env/bin/gunicorn", line 11, in <module> sys.exit(run()) File "/home/web/git/myprojc/.env/lib/python2.7/site-packages/gunicorn/app/wsgiapp.py", line 74, in run WSGIApplication("%(prog)s [OPTIONS] [APP_MODULE]").run() File "/home/web/git/myprojc/.env/lib/python2.7/site-packages/gunicorn/app/base.py", line 203, in run super(Application, self).run() File "/home/web/git/myprojc/.env/lib/python2.7/site-packages/gunicorn/app/base.py", line 72, in run Arbiter(self).run() File "/home/web/git/myprojc/.env/lib/python2.7/site-packages/gunicorn/arbiter.py", line 231, in run self.halt(reason=inst.reason, exit_status=inst.exit_status) File "/home/web/git/myprojc/.env/lib/python2.7/site-packages/gunicorn/arbiter.py", line 344, in halt self.stop() File "/home/web/git/myprojc/.env/lib/python2.7/site-packages/gunicorn/arbiter.py", line 393, in stop time.sleep(0.1) File "/home/web/git/myprojc/.env/lib/python2.7/site-packages/gunicorn/arbiter.py", line 244, in handle_chld self.reap_workers() File "/home/web/git/myprojc/.env/lib/python2.7/site-packages/gunicorn/arbiter.py", line 524, in reap_workers raise HaltServer(reason, self.WORKER_BOOT_ERROR) gunicorn.errors.HaltServer: <HaltServer 'Worker failed to boot.' 3> this is the stacktrace I get when I try to start the project, How to fix ImproperlyConfigured in django 1.7? -
django user_permissions.clear() not work
My user_permissions.clear() and remove() can't work at all! The two print is same. And when I create a new user, the user always contains all of models permissions. class ChangeTeacherPermission(APIView): def post(self, request): user = self.request.GET.get('user', None) user = User.objects.get(username=user) print(user.get_all_permissions()) user.user_permissions.clear() print(user.get_all_permissions()) permissions = json.loads(self.request.POST.get('obj'))['permissions'] flag = json.loads(self.request.POST.get('obj'))['flag'] class User(BaseUser): class BaseUser(AbstractBaseUser, PermissionsMixin): -
Django save and enter data after API call in views
I have 2 django project, D1 and D2. D1 has a table call T1 and D2 has a table call T2. So i have a view in D1 that do api call to the api in D2 and save the value that i get after a POST request into T1. But i also want to be able to enter data in other field of table T1. example: t2 only has book field, t1 has book and author field. When D1 do a post method to t2 in D2, it will return a book value which will be save into t1 but i also want the user to enter the author themself. How do i do it ? Here is my code models.py In D1: class T1(models.Model): book = models.CharField(max_length=10, blank=True, null=True) author = models.CharField(max_length=10, blank=True, null=True) In D2 class T2(models.Model): book = models.CharField(max_length=10, blank=True, null=True) views.py @csrf_exempt def my_django_view(request): if request.method == 'POST': r = requests.post('http://127.0.0.1:8000/api/test/', data=request.POST) else: r = requests.get('http://127.0.0.1:8000/api/test/', data=request.GET) if r.status_code == 201 and request.method == 'POST': data = r.json() testsave_attrs = { "book": data["book"], } testsave= T1.objects.create(**testsave_attrs) return HttpResponse(r.text) elif r.status_code == 200: # GET response return HttpResponse(r.json()) else: return HttpResponse('Could not save data') -
Invalid literal for int() with base 10 in template with multiple forms
I have a form that only links to one of the fields in one of my models. I'm trying to save the form, but I keep getting errors and don't know what to change. Models.py class FunctionManager(models.Manager): def editover(self, Function_id, postData): woo = Function.objects.get(id=Function_id) woo.new = postData["new"] woo.save() class Function(models.Model): tableA = models.CharField(max_length=50) new = models.TextField() def __str__(self): return str (self.tableA, self.id) objects = FunctionManager() views.py def function_page(request, Function_id): assignments = Function.objects.get(id=Function_id) context = { 'assignments': assignments, } return render (request, 'project/function.html', context) def new_save(request, Function_id): newest = WarFightingFunction.objects.editover('Function_id', request.POST['new']) return redirect ('project/function.html') urls.py url(r'^function_page/(?P<Function_id>\d+)$', views.function_page, name "function_page"), url(r'^new_save/(?P<Function_id>\d+)/$', views.new_save, name = "new_save") html <div id=new> <form action= "/SCS/new/{{assignments.id}}/" method="POST"> {% csrf_token %} <textarea name="new" id="Obox"></textarea> <input class="save" type="submit" value="Save"> </form> </div> What am I doing wrong? Thanks in advance. -
Add a field in Serializer, but the DRF is no the field
I have the Serializer to add a user_id field, see my bellow code: My PhysicalServerManualGenerateOrderSerialzier: class PhysicalServerManualGenerateOrderSerialzier(ModelSerializer): physicalserver_model = serializers.IntegerField(write_only=True) operate_system = serializers.CharField(write_only=True) extra_desc = serializers.CharField(allow_null=True, write_only=True) user_id = serializers.IntegerField(write_only=True) class Meta: model = Order fields = [ "billing_type", "buytime", "count", "physicalserver_model", "operate_system", "extra_desc", "user_id", # you see, I add the `user_id` there. ] def to_representation(self, instance): serialized_data = super(PhysicalServerGenerateOrderSerialzier, self).to_representation(instance) serialized_data['order_num'] = instance.order_num serialized_data['order_type'] = instance.order_type serialized_data['order_status'] = instance.order_status serialized_data['billing_type'] = instance.billing_type serialized_data['buytime'] = instance.buytime serialized_data['count'] = instance.count serialized_data['cost'] = instance.cost serialized_data['ctime'] = instance.ctime serialized_data['product_describe'] = instance.product_describe return serialized_data def create(self, validated_data): user_id = validated_data.get("user_id") user = User.objects.get(id=user_id) try: order = getOrder(user=user, validated_data=validated_data) except Exception as e: order = None return order My PhysicalServerManualGenerateOrderAPIView: class PhysicalServerManualGenerateOrderAPIView(CreateAPIView): """ generate order """ serializer_class = PhysicalServerManualGenerateOrderSerialzier permission_classes = [] queryset = Order.objects.all() But in the DRF, there is no user_id option: -
Specifying basic authentication credentials for a Django REST framework API client
I'm trying to run some tests to go with the Django REST tutorial (see source code). I got a solution working using the APIClient's .force_authenticate method, but I'd prefer to construct the credentials more explicitly. I've tried the following: import json import base64 from django.contrib.auth.models import User from django.test import TestCase from rest_framework.test import APITestCase, force_authenticate from snippets.models import Snippet class SnippetTestCase(APITestCase): def setUp(self): self.username = 'john_doe' self.password = 'foobar' self.user = User.objects.create(username=self.username, password=self.password) # self.client.force_authenticate(user=self.user) credentials = base64.b64encode(f'{self.username}:{self.password}'.encode('utf-8')) self.client.credentials(HTTP_AUTHORIZATION='Basic {}'.format(credentials)) def test_1(self): response = self.client.post('/snippets/', {'code': 'Foo Bar'}, format='json') self.assertEqual(response.status_code, 201) This test passed with the commented-out line with .force_authenticate, but fails in its current form, which I based on Using Basic HTTP access authentication in Django testing framework: Kurts-MacBook-Pro:rest-framework-tutorial kurtpeek$ python manage.py test Creating test database for alias 'default'... System check identified no issues (0 silenced). F ====================================================================== FAIL: test_1 (tutorial.tests.SnippetTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/Users/kurtpeek/Documents/source/rest-framework-tutorial/tutorial/tests.py", line 23, in test_1 self.assertEqual(response.status_code, 201) AssertionError: 403 != 201 ---------------------------------------------------------------------- Ran 1 test in 0.022s FAILED (failures=1) Apparently, the authentication is not working because I'm getting a 403 Forbidden error. Any ideas on how to fix this? -
How can send data from nodemcu/arduino to raspberry pi via wifi?
I made a webapp using django framework and setup a web server in raspberry pi 3 following this tutorial(using gunircon and nginx), also a set up the raspberry as access point.In the other hand, I have sensor that is measuring, this sensor was made using Nodemcun and de Arduino IDE,I want send de data from nodemcu to rapsberry pi via WiFi and get de data in raspberry and save it in my database, my question is howt to do it using python? I have been reading and I found that that is possible using telnet but I don't know how to do it. some clue, information or tutorial pleas. Thanks a lot -
How to handle legacy php-generated passwords in Django
I'm moving a server from php(5.6.32) to Django(1.11.7) that contains thousands of users with passwords encrypted using the password_hash(<pwd>, PASSWORD_DEFAULT) function. Does Django have support for this encryption? It appears neither theBCryptPasswordHasher or the BCryptSHA256PasswordHasher handle this. I believe a custom hasher may be required, but its not clear how to handle this. -
Django: displaying a foreign key of a model in template
this is a rather basic question (I'm new to Django) i'm having trouble displaying a foreign key in the template. i have this model which has 'employer' as a ManyToManyField in the Job model: from django.db import models # Create your models here. class Employer(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=50,default="") business = models.CharField(max_length=25, default="") team = models.IntegerField() about = models.TextField(max_length=1000) country = models.CharField(max_length=25, default="") city = models.CharField(max_length=25, default="") class Job(models.Model): date = models.DateTimeField(auto_now_add=True, blank=True) specialism = models.CharField(max_length=25) employer = models.ManyToManyField(Employer) I try to get all jobs that contains "Computers" as specialism: from django.shortcuts import render from .models import Job, Employer # Create your views here. def index(request): return render(request, 'pages/index.html') def post_list(request): jobs = Job.objects.all().filter(specialism="Computers") return render(request, 'wall.html',{'jobs':jobs}) And for every job i wanna display the employer name in the template: <!DOCTYPE html> <html> <head> <title></title> </head> <body> <center><h1>WALL</h1></center> {% block content %} {{jobs.count}} {% for job in jobs %} <h2>specialism :{{job.specialism}} employer: {{job.employer.name}}</h2> {% endfor %} {% endblock %} </body> </html> I get None as a value for job.employer.name. so how can i display the name of the employer for every job? -
Django: I cant create a model, I got this error:[pylint] E0001:invalid syntax (<string>, line 8)
file: models.py from __future__ import unicode_literals from django.db import models class Register(models.Model) name =models.Charfield(maxlength=100,blank=True,null=True) email =models.EmailField() timestamp = models.DateTimeField(auto_now_add=True,auto_now=False) def__unicode__(self): return self.mail def__str__(self): return self.mail error: [pylint] E0001:invalid syntax (, line 8) I try to execute command-line: python manage.py makemigrations message is: No changes detected. I use python 3.7 -
Adding tests to the Django REST framework tutorial
I'm trying to replace an existing function-based view using the login_required decorator with a Django REST framework API using a ModelViewSet. However, it seems like the authentication works a bit differently. In order to try to adapt my unit tests to the Django REST framework case, I cloned https://github.com/encode/rest-framework-tutorial and added a tests.py at the top level directory: import json from django.contrib.auth.models import User from django.test import TestCase, Client from snippets.models import Snippet class SnippetTestCase(TestCase): def setUp(self): self.username = 'john_doe' self.password = 'foobar' self.user = User.objects.create(username=self.username, password=self.password) self.client = Client() self.snippet = Snippet.objects.create(owner=self.user, code="Foo Bar") def test_1(self): self.client.login(username=self.username, password=self.password) response = self.client.post( path='http://localhost:8000/snippets/1/', data=json.dumps({'code': 'New code'}), content_type="application/json") self.assertEqual(response.status_code, 201) However, this returns a 403 Forbidden response: Kurts-MacBook-Pro:rest-framework-tutorial kurtpeek$ python manage.py test Creating test database for alias 'default'... System check identified no issues (0 silenced). F ====================================================================== FAIL: test_1 (tutorial.tests.SnippetTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/Users/kurtpeek/Documents/source/rest-framework-tutorial/tutorial/tests.py", line 23, in test_1 self.assertEqual(response.status_code, 201) AssertionError: 403 != 201 ---------------------------------------------------------------------- Ran 1 test in 0.049s FAILED (failures=1) Destroying test database for alias 'default'... On the other hand, using HTTPie with the -a flag works fine: Kurts-MacBook-Pro:rest-framework-tutorial kurtpeek$ http -a kurtpeek:foobar123 POST http://localhost:8000/snippets/ code="print 123" HTTP/1.1 201 Created Allow: GET, POST, HEAD, OPTIONS … -
Linking user to other tables in django
I have the below in my models.py file: class Film(models.Model): title = models.CharField(max_length=200) director = models.CharField(max_length=200) description = models.CharField(max_length=200) pub_date = models.DateField('date published') class Comment(models.Model): film = models.ForeignKey(Film, on_delete=models.CASCADE) body = models.CharField(max_length=200) When I logged into Django admin I added some films, and then added some comments, selecting which film object the comment related to. I then created a couple of users via the admin panel also. I would like my relationships to be: Film can have many comments / Comments belong to film User can have many comments / Comments belong to user I think, like with comments and films, I just need to define user as a foreign key to comment. I am struggling to do this. I am working through the Django tutorials but I can't see the tutorials covering how I can link other tables to the user. I thought I would be able to do something like this: user = models.ForeignKey(User, on_delete=models.CASCADE) While importing User like this: from django.contrib.auth.models import User The result at the moment is if I keep user = models.ForeignKey(User, on_delete=models.CASCADE) I get err_connection_refused -
disable logout after adding user django
I need to create admin panel in django , admin will be able to add students"which extended from users " , I finally be able to add them , but after that I get "'AnonymousUser' object has no attribute '_meta' User is added to the database correctly , But django logged me out ! How Can I keep my current user session ! class student(models.Model): Computers = 1 Communications = 2 Dep_CHOICES = ( (Computers, 'Computers'), (Communications, 'Communications'), ) user = models.OneToOneField(User, on_delete=models.CASCADE) dep = models.PositiveSmallIntegerField(choices=Dep_CHOICES, null=True, blank=True) deg = models.FloatField(null=True, blank=True) def __str__(self): # __unicode__ for Python 2 return self.user.username def create_user_profile(sender, instance, created): if created: student.objects.create(user=instance) def save_user_profile(sender, instance , **kwargs): instance.student.save() class UserForm(ModelForm): class Meta: model = User fields = ('username', 'email', 'password') class studentForm(ModelForm): class Meta: model = student fields = ('dep', 'deg') The view def add_stu(request): if request.method == 'GET': return render(request, "add_student.html") else: user_form = UserForm(request.POST, instance=request.user) profile_form = studentForm(request.POST, instance=request.user.student) user_form.save() profile_form.save() -
pytest django TestCase give strange failures
I have a very simple class which fails on any version of pytest>3.0.0. from django.test import TestCase class TestTestCase(TestCase): """Tests for the TestCase class.""" def test_that_client_exists(self): """Assert that the class has a client.""" assert self.client I am using the following version: platform Linux Python 2.7.11 pytest-3.3.1 py-1.5.2 pluggy-0.6.0 django-2.9.2 And I get the following error: self = <myproject.tests.test_test_case.TestTestCase testMethod=test_that_client_exists> def test_that_client_exists(self): """Assert that the class has a client.""" > assert self.client E AttributeError: 'TestTestCase' object has no attribute 'client' However, if I downgrade to pytest==3.0.0 and pluggy-0.3.1, the code executes without any issues. My question is this, what is going on? What could be causing this? It is as if pytest is calling the test_that_client_exists but is not calling __call__ which calls _pre_setup. Has anyone seen anything like this? -
Django Form: NoReverseMatch
Getting an error: NoReverseMatch: Reverse for 'post_new' not found. 'post_new' is not a valid view function or pattern name. my form in base.html: > <form action="{% url 'post_new' %}" method="post"> > {% csrf_token %} > Name:<br> > <input type="text" name="name"><br> > Text:<br> > <input type="text" name="text"> > <input type="submit" value="Submit"> </form> views.py: def post_new(request): posts = Post.objects.all() name = request.POST['name'] print(name) return render(request, 'blog/base.html', {'posts': posts}) urls.py: urlpatterns = [ url(r'^$', views.base), url(r'^post_new/$', views.post_new, name='post_new'), ] -
Pass JSON data in Django context
Normally, if I want to return JSON data from a Django view, I can use a JsonResponse like so: from django.http import JsonResponse def my_view(request): return JsonResponse({'my_key': 'my_value'}) That data is sent to the frontend as a JavaScript object that I can immediately use. I'd like that same ease of use added to the context of a view, like so: class WebsiteView(TemplateView): template_name = 'index.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['my_var'] = {'my_key': 'my_value'} return context However, rendering the template with {{ my_var }} gives: {&quot;my_key&quot;: &quot;my_value&quot;} Ultimately, what I want is for {{ my_var }} to return the plain string rather than the HTML encoded version: {"my_key": "my_value"} This way, I can easily load it into a JavaScript object with JSON.parse('{{ my_var }}'). I know that one way to achieve this is by manually unescaping the HTML entities, but I was wondering if there was a better way to do this. -
Setting up Ubuntu Server 16.04 with Apache to run Django
I have Ubuntu Server 16.04 running Achape. I am trying to get Apache to run Django. So far I have created a project in Django and can get it to run on port 80 by using the command "sudo python3 manage.py runserver 192.168.1.230:80". I would like to have Apache setup to run Django so I do not have to do this command. I have looked for 6 hours now and tried 10+ different ways to do this and can't get it to work. I usually end up getting a 500 Internal Error. I have changed the apache2.conf file, and 000-default.conf file. What should I do? -
troubles modules Django mas os - pycharm
dears. I'm new in python/django. I just try Install and configure an enviroment from my ubuntu to my mac os. I've installed Python 3.6 , Django 2.0 and i'm using pycharm. When I tried run with "runserver", I got this error: /Users/fabio/Documents/projects/lib/python3.6/site-packages/magic/__pycache__/_cffi__xa0d5132dx54cebdac.c:208:10: fatal error: 'magic.h' file not found #include <magic.h> ^~~~~~~~~ 1 error generated. /Users/fabio/Documents/projects/lib/python3.6/site-packages/magic/__pycache__/_cffi__xa0d5132dx54cebdac.c:208:10: fatal error: 'magic.h' file not found #include <magic.h> ^~~~~~~~~ 1 error generated. Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x10ea68268> Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/distutils/unixccompiler.py", line 118, in _compile extra_postargs) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/distutils/ccompiler.py", line 909, in spawn spawn(cmd, dry_run=self.dry_run) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/distutils/spawn.py", line 36, in spawn _spawn_posix(cmd, search_path, dry_run=dry_run) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/distutils/spawn.py", line 159, in _spawn_posix % (cmd, exit_status)) distutils.errors.DistutilsExecError: command '/usr/bin/clang' failed with exit status 1 During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Users/fabio/Documents/projects/lib/python3.6/site-packages/cffi/ffiplatform.py", line 55, in _build dist.run_command('build_ext') File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/distutils/dist.py", line 974, in run_command cmd_obj.run() File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/distutils/command/build_ext.py", line 339, in run self.build_extensions() File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/distutils/command/build_ext.py", line 448, in build_extensions self._build_extensions_serial() File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/distutils/command/build_ext.py", line 473, in _build_extensions_serial self.build_extension(ext) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/distutils/command/build_ext.py", line 533, in build_extension depends=ext.depends) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/distutils/ccompiler.py", line 574, in compile self._compile(obj, src, ext, cc_args, extra_postargs, pp_opts) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/distutils/unixccompiler.py", line 120, in _compile raise CompileError(msg) distutils.errors.CompileError: … -
Django model history by date and datetime
Assume I have model like this: class Account(models.Model): balance = models.IntegerField() debt = models.IntegerField() history = HistoricalRecords() I'm using django-simple-history to get instance of the model as it would have existed at the provided date and time: inst = Account.history.as_of(datetime.datetime.now().date) It's working fine, but I want to get instance where debt field is represented as it would have existed at the provided date and time, and then debt field will be most recent of that date. I don't know if this is possible, didn't find anything about that. -
Prefetch the contents of files referenced by the ORM
My situation is that I'm using the Django ORM to fetch a list of objects, each with a file. I then need to access the file-data for each and every object in the list. We're hosting our files on S3, and it seems to take a long time every time I call f.read() I'm wondering, is there a way to pre-fetch the contents of the file, so that f.read() doesn't have to make another round-trip? Anything else I can do to speed this up? Any help is appreciated, and let me know if there is more I can clarify. -
How to update a Wagtail Page
I am using a wagtail_hook to update a Page object and am running into trouble. More specifically, when an end-user hits the "Save draft" button from the browser I want the following code to fire. The purpose of this code is to change the knowledge_base_id dynamically, based on the results of the conditional statements listed below. def sync_knowledge_base_page_with_zendesk2(request, page): if isinstance(page, ContentPage): page_instance = ContentPage.objects.get(pk=page.pk) pageJsonHolder = page_instance.get_latest_revision().content_json content = json.loads(pageJsonHolder) print("content at the start = ") print(content['knowledge_base_id']) kb_id_revision = content['knowledge_base_id'] kb_active_revision = content['kb_active'] if kb_active_revision == "T": if kb_id_revision == 0: print("create the article") content['knowledge_base_id'] = 456 #page_instance.knowledge_base_id = 456 # change this API call else: print("update the article") elif kb_id_revision != 0: print("delete the article") content['knowledge_base_id'] = 0 #page_instance.knowledge_base_id = 0 print("content at the end = ") print(content['knowledge_base_id']) #page_instance.save_revision().publish So when the hook code fires, it updates the draft with all the info EXCEPT the knowledge_base_id. However when I change the knowledge_base_id like this (seen commented out above) page_instance.knowledge_base_id = 0 And save it like this (also seen commented out above) page_instance.save_revision().publish() It saves the updated knowledge_base_id BUT skips over the other revisions. In short, what the heck am I doing wrong. Thanks in advance for the assist. …