Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Token_for_business to check the user's presence on Facebook
Is it possible to check if a user is on Facebook with token_for_business? In the database, the column holding the records for token_for_business exists and contains randomly written token_for_business. But I do not know which ones are real. I'm looking for a verification action for this. -
Max_length in Django CharFields
The Django docs indicate that: The max_length is enforced at the database level and in Django’s validation. What, exactly does this mean? I have a routine to parse an input CSV file to create some models, and an over-length Name field got in there along the way as I created objects using: new_standard = Standard.objects.create(Name=lname,ShortName=sname,calcmethod=method,Description=descr,course=course,Order=stdnum) new_standard.save() The error was only raised later, as the user tried to edit the object using a form (which wouldn't validate). When using the same form to create objects, the input field won't allow typing past the 30th character, but my manual method seems to allow the over-length field to be created. How do I avoid this (apart from manually truncating strings after checking field lengths, which I could do, but which seems like a lot of hassle - seems like I could handle it in the form or DB)? Now that I have some of these time bombs in my DB, what's the easiest way to get rid of them? -
Unit test in Django: using self.assertIn() to find text in key/value pair
I'm trying to write a unit test for my Django app using self.assertIn() This is my unit test: def test_user_get_apps_meta(self): myuser = User.objects.get(email='theemail@gmail.com') tagline = 'the text' self.assertIn(tagline, myuser.get_apps()) The result of myuser.get_apps() is a list of dictionaries. In one of those dictionaries is indeed the tagline text I'm looking for: 'the text' But I'm getting an error when I run the test: self.assertIn(tagline, myuser.get_apps()) AssertionError: 'the text' not found in [{'logo_app_alt': 'the text', '...},{},{}] Am I not using self.assertIn() correctly? Is there a way to check if certain text is the value of a key/value pair in a dictionary? -
Python web development framework for a dashboard application
I need help in choosing a Python web framework for a rewrite of a dashboard application. I listed all frameworks from the official community list that are full-stack and have had an update since January 2017. I've removed all frameworks from the list that had very little stars and contributors on Github, weren't well-documented and/or had too little in-the-box functionality. I came up with these 4 candidates: Django web2py Tornado CubicWeb The most important requirements for my project are: widgets on the dashboard visualize values in near-real time, received from a LOT of web services, either using polling or WebSockets, using a client side single page application must be possible, I want well-structured code and prefer an MVC web framework, some data (dashboard & widget composition) must be stored in a database on the server the server must be able to read and write files rapidly, and in a private folder, there's a need for user login and sharing of dashboards among users and groups of users, and access rule checking for various pages and functionality I want a framework that has a manageable learning curve. What seems to be the best option? -
Django View Returns 502 Bad Gateway on Google App Engine
I've created an Django app and deployed in on GAE. However, whevever I run the page which executes a script xxx.appspot.com/script, it returns 502 Bad Gateway. As a side note, everything works fine locally, and 502 appears after around 30 seconds (I'm assuming the script simply takes longer than that to execute and the server doesn't wait enough time). My app.yaml is: runtime: python env: flex entrypoint: gunicorn -b :$PORT djangoapp.wsgi resources: memory_gb: 4 views.py (Responsible for rendering the page) def model(request): try: model = joblib.load('static/model.pkl') # run the LONG CODE which runs model predictions, outputs it etc. return render(request, "queries/success.html") except Exception as e: logging.critical(e) return render(request, "queries/fail.html") Now I can come up with 2 issues: 1) Nginx server is not giving enough time to execute the command and spits out the error. 2) The model is not loaded on GAE properly (since it's located in the STATIC directory which maybe doesn't exist on GAE - I'm not sure since I can't see the files used by GAE). In my settings.py, I have defined where to get static files: STATIC_URL = 'https://storage.googleapis.com/django/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_DIRS = [os.path.join(BASE_DIR, "staticfiles"),] TEMPLATE_DIRS = (os.path.join(BASE_DIR, 'templates'),) -
Deploying Django on AWS
I'm looking to deploy a django app on AWS (either elastic beanstalk or through ec2) but after lot's of searching can't actually find a tutorial that works for me. Using http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create-deploy-python-django.html I've managed to get my application uploaded but can't find anything about how to create a database for it or manage it properly. (as in I don't know how to access logs for it as I can't see the instance this is running on my aws dashboard) I realise this is a very open ended request but any direction towards an up to date good tutorial on this would be hugely appreciated. -
Get list from two models (With addtional fields). Make Subquery
I have models Reserved and Room (default status is Free). And i want get list of all Rooms. Their statuses is Reserved (I have such table) Free (not price, state) Busy So in short i need to get all Rooms with their status. I don't need status fields and will not add it. No status field in my models. How can i get certain statuses? Shortly model class Room(models.Model): # Default all rooms are Free (Rooms state) number = models.ForeignKey(RoomNumber) expiry_date = models.DateTimeField() class Reserved(models.Model): visitor = models.ForeignKey(Visitor, on_delete=models.PROTECT) room = models.OneToOneField(Room) reserved_date = models.DateTimeField() begin_date = models.DateTimeField() I tried to do Subquery but no result :( reserved = Reserved.objects\ .filter(room=OuterRef('pk'))\ .filter(begin_date=timezone.now())\ .values(count=Count('pk')) Room.objects.annotate(reserved=Subquery(reserved[:1])) If 1 room is Reserved if 0 empty -
Learn about user status with token_for_business on Facebook
I want to delete the random facebook business id that was entered into the database years ago. An idea for that came to mind. Putting business id in the database on the facebook verification test. I entered the Facebook development environment. Here I wanted to test several business_ids in db. But I did not get the result I wanted. In the end, can I check with the token_for_business id to see if the user actually exists? -
Docker container does not recognize DJango Formtools
I have some code that uses DJango Form Tools (in particular, the SessionWizardView) . From what I can see, the Formtools appears to work outside a Docker Container but fails when it is used within one. The environment where it is working is development. The Docker container where it is not wokring is Production. The error message one gets is (in the log of the running contaner): from formtools.wizard.views import SessionWizardView ModuleNotFoundError: No module named 'formtools' **I have installed formtools on the C:\Users\dgmufasa>pip install django-formtools Requirement already satisfied: django-formtools in c:\work\software\python64bitv3.6\lib\site-packages Requirement already satisfied: Django>=1.8 in c:\work\software\python64bitv3.6\lib\site-packages\django-1.11.7-py3.6.egg (from django-formtools) Requirement already satisfied: pytz in c:\work\software\python64bitv3.6\lib\site-packages\pytz-2017.3-py3.6.egg (from Django>=1.8->django-formtools) I have added it to INSTALLED_APPS in the settings.py file INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', [..snip ..] 'formtools', ] I have used it as part of a program: from django.shortcuts import render, render_to_response from formtools.wizard.views import SessionWizardView #from django.contrib.formtools.wizard.views import SessionWizardView from django.contrib.auth.decorators import login_required [... snip ...] In this area (development) it all works - but - when taking the EXACT same code, creating a Docker file and putting it into production, I get errors. **requirements.txt for Docker build** file Django==1.11.7 psycopg2 Pillow==4.3.0 bcrypt==3.1.4 cffi==1.11.2 django-formtools django-phonenumber-field==1.3.0 googlemaps==2.5.1 geocoder==1.33.0 geopy==1.11.0 … -
Dynamic read-only field in Django Admin
In Django Admin I want all fields to be: 1) editable on creation 2) some of them on updating ( based on the instance fields values on creation). For example: 2-1. If attribute a has value the fields corresponding to attributes c and b to be readonly 2-2. If attributes are empty after creation, should not be editable on updating -
Understanding a hairy SQL situation
I have a Django app with pymysql to connect to my MySQL instance. Following is my python code for a post request: if request.method == 'POST': body = json.loads(request.body.decode('utf-8')) db = connect_to('table_name', 'key') for json_variable in body['json_key']: record = db.findFirst({'user_id': user_id, 'date': body['date']}) if not record: db.create({'column_name':value}) else: db.update({'column_name':value}, {'user_id': user_id}) In this connect_to, findFirst, create and update are helper methods to connect to the database, find first record with parameters, create a new record and update a table with parameter 1 where parameter 2 is true. The issue is that in many situations, despite a record being present a new one is created and not updated as it should be. The django app itself is on heroku and the mysql instance is on AWS. -
celery task not processed by celery
total celery and django noob here, so sorry if the problem is trivial. Basically the problem is that any function defined by @app.task is not being processed by celery, it just runs normally as if celery isn't there. My celery_app.py file is - from __future__ import absolute_import import os from celery import Celery from django.conf import settings # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings') app = Celery(broker=settings.CELERY_BROKER_URL) app.config_from_object('django.conf:settings') app.autodiscover_tasks() if __name__ == '__main__': app.start() While my tasks.py file is - from project.celery_app import app @app.task def mytask(): ... I get the following output on running celery in the terminal - -------------- celery@LAPTOP v4.1.0 (latentcall) ---- **** ----- --- * *** * -- Windows-10-10.0.16299-SP0 2017-12-20 19:27:24 -- * - **** --- - ** ---------- [config] - ** ---------- .> app: __main__:0x229ce2884e0 - ** ---------- .> transport: amqp://user:**@localhost:5672/myvhost - ** ---------- .> results: disabled:// - *** --- * --- .> concurrency: 8 (solo) -- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker) --- ***** ----- -------------- [queues] .> celery exchange=celery(direct) key=celery [tasks] . tasks.send_sms [2017-12-20 19:27:24,085: INFO/MainProcess] Connected to amqp://user:**@127.0.0.1:5672/myvhost [2017-12-20 19:27:24,101: INFO/MainProcess] mingle: searching for neighbors [2017-12-20 19:27:25,126: INFO/MainProcess] … -
Django ORM Count by Related Field
I have the following models: class Profile(models.Model): pass class Team(models.Model): ... members = models.ManyToManyField("main.Profile", through='main.TeamMember') class TeamMember(models.Model): profile = models.ForeignKey('Profile') team = models.ForeignKey('Team') role = models.CharField(max_length=255) So, I try to order teams by count of profiles with a certain role, and I had a query, which doesn't work: Team.objects.filter(members__role='ExampleRole').annotate(example_role_count=Count('members')).order_by('example_role_count') It raises the following Exception: django.core.exceptions.FieldError: Related Field got invalid lookup: role because role is a TeamMember field, not Profile. So, how can I achieve ordering by count of members with a specified role? -
Django Listview for model related to user returning "No user" error
I'm trying to produce a list of user addresses so that a user can review and then update, delete etc... Currently I'm using ListView with: class AddressListView(LoginRequiredMixin, ListView): model = Address def get_object(self): return self.model.objects.get(user=self.request.user.pk) with the Address model: class Address(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL) house_name = models.CharField(max_length=255, null=True) house_number = models.CharField(max_length=255, null=True) street_name = models.CharField(max_length=255, null=True) ....... And the url pattern: .... url( regex=r'^address/$', view=views.AddressListView.as_view(), name='address_list' ), ... However when I try to request that view I get an error "Page not found (404), No user found matching the query" -
How to rectify the error in defining the forms.ModelForm widgets
enter image description hereI am getting the following error when assigning a widget to forms.ModelForm. Please suggest how to rectify this error. forms.py from django import forms from django.forms import ModelForm, CharField from .models import * class CreateTaskMaster(forms.ModelForm): class Meta(): model = TaskMaster fields = ["sid", "tasktype", "task_title", "task_description", "datacenter", "priority", "sourceincident", "processingteam", "duedate"] widgets = { 'duedate': CharField(widget=forms.TextInput(attrs={'class': 'form- control mr-sm-2'})), } Model.py Class TaskMaster(models.Model): sid = models.CharField(max_length=3) processor = models.ForeignKey(User,null=True) tasktype = models.ForeignKey(TaskTypeTable, null=True) task_title = models.TextField(null=True) task_description = models.TextField(null=True) datacenter = models.ForeignKey(DatacenterTable,null=True) priority = models.ForeignKey(PriorityTable, null=True) status = models.ForeignKey(StatusTable,default=1, null=True) pid = models.IntegerField(null=True) sourceincident = models.URLField(null=True) errorincident = models.URLField(null=True) processingteam = models.ForeignKey(TeamTable, null=True) createddate = models.DateField(("Date"), default=datetime.date.today) duedate = models.DateField(("Date"), default=datetime.date.today) istaskactive = models.BooleanField(default=True) class Meta: ordering = ('duedate',) -
How to create equivalent LEFT JOIN query in Django's ORM (1.11)
With the following model setup (simplified for brevity): class Claim(models.Model): permalink = models.SlugField(max_length=255, blank=True, unique=True) author = models.ForeignKey(get_user_model(), db_index=True, on_delete=models.SET_NULL, null=True, blank=True) collaborators = models.ManyToManyField(get_user_model(), through='ClaimCollaborator', related_name='claims') # ...other fields class ClaimCollaborator(models.Model): claim = models.ForeignKey(Claim, db_index=True, on_delete=models.CASCADE) user = models.ForeignKey(get_user_model(), db_index=True, on_delete=models.CASCADE) # ...other fields I am trying to replicate the following SQL query in Django's ORM. SELECT * FROM claim c LEFT JOIN claim_collaborator cc ON cc.claim_id = c.id WHERE c.permalink = 'foo-bar' AND (c.author_id = 2 OR cc.user_id = 2) The logic I believe should be straightforward with usage of django.db.models.Q, but the bit I'm struggling on is the LEFT JOIN. Bit of a Django ORM noob, and I have attempted various usage of select_related() with the ClaimCollaborators model to no avail. Any ideas? -
Django Heroku deployment: OperationalError at /users/login/ no such table: auth_user [duplicate]
This question already has an answer here: Django: Deploying an application on Heroku with sqlite3 as the database 1 answer I built a django web app, using sqlite3 as database. my app works fine (create superuser, login as admin, and use the app) in local environment, but after I deploy it on Heroku I encountered issues: 1. 'heroku run python manage.py migrate' doesn't set up the live database (db.sqlite3) on Heroku. (cannot find any .sqlite3 files in /app) local$ heroku run python manage.py migrate local$ heroku run bash # cannot find any .sqlite3 files on live database ~$ ls manage.py Procfile requirements.txt runtime.txt myproject myapp users ~$ ls myproject __init__.py __pycache__ settings.py static urls.py wsgi.py So I typed 'python manage.py migrate' again inside 'heroku run' bash, creating db.sqlite3. ~$ python manage.py migrate ~$ ls myproject db.sqlite3 __init__.py __pycache__ settings.py static urls.py wsgi.py But, as soon as I exit the bash, the .sqlite3 disappears again. ~$ exit local$ heroku run bash ~$ ls dir_project # no db.sqlite3 file __init__.py __pycache__ settings.py static urls.py wsgi.py 2. cannot login as created superuser on live app. local$ heroku run bash ~$ python manage.py migrate ~$ python manage.py createsuperuser username: example_admin email: example@mail.com password: **** … -
avoid Circular import in Django
I have two models Company and Actions: from companies.models import Company class Action(models.Model): company = models.ForeignKey(Company, blank=True, null=True, related_name='activity', on_delete=models.CASCADE) I have then an utility in utils.py from .models import Action def create_action(user, verb, target_name=None, target=None): action = Action(user=user, verb=verb, target=target) This utility I called in Company model on def save, so on Company Model I have: import not.utils import create_action so Action Model import Company Model as FK, utils import Action Model, and Company Model import utils Now, because of circular import Django give an error: ImportError: cannot import name 'Company' I saw some q/a here to use import directly (without from) I tried but didn't worked -
max_length does not work
I have such field in my model: name = models.CharField(max_length=20, default='Anonymous') But when I enter more characters in that field, there is no errors, I can enter any amount of characters. And I can do it in my view, do it in admin/, there is no errors anyway. Somebody adviced me to make .full_clean() before saving entries, but it does not affect, this field still allows to enter more than 20 characters. Same with other fields. And I very, very, very sorry for my bad english. -
Django-rest-framework: No module named 'rest_framework.reverse_lazy'
I have tried reverse of DRF it works from rest_framework.reverse import reverse reverse("posts-api:article_year_month",args=(2017,1)) '/api/gaurnitai/posts/2017/1' whereas the reverse_lazy is not working: from rest_framework.reverse_lazy import reverse_lazy reverse_lazy("posts-api:article_year_month",args=(2017,1),request=request) ModuleNotFoundError: No module named 'rest_framework.reverse_lazy' -
PushPin with django - publish is not happending
I have two docker containers one for pushpin from here and one for my django project which i have created locally. My settings file contains following code for pushpin MIDDLEWARE = [ 'django_grip.GripMiddleware', ... ] GRIP_PROXIES = [{'control_uri': 'http://localhost:5561'}] And my views are as follows: from future import unicode_literals from django.shortcuts import render from django.http import HttpResponse from django.views import View from json import dumps from gripcontrol import HttpStreamFormat from django_grip import set_hold_stream, publish from django.views.decorators.csrf import csrf_exempt from django.utils.decorators import method_decorator # Create your views here. counter = [0] * 10 class HelloWorld(View): @method_decorator(csrf_exempt) def dispatch(self, request, *args, **kwargs): return super(HelloWorld, self).dispatch(request, *args, **kwargs) def get(self, request, cnt_id): cnt_str = 'counter-%s' % cnt_id cnt_id = int(cnt_id) data = {"counter": counter[cnt_id]} response = dumps(data) + '\n' set_hold_stream(request, cnt_str) return HttpResponse(response, content_type='text/plain') def post(self, request, cnt_id): cnt_str = 'counter-%s' % cnt_id cnt_id = int(cnt_id) global counter counter[cnt_id] += 1 data = {"counter": counter[cnt_id]} resp = dumps(data) + '\n' publish(cnt_str, HttpStreamFormat(resp)) return HttpResponse(resp, content_type='text/plain') Now whenever i do curl to pushpin it halts but does not get updated result published whenever i do post request #$ curl http://localhost:7999/hello/say/1/ {"counter": 2} It does not get updated result even after hitting post request. But … -
Django 2.0 Tutorial - Error when executing python3 manage.py makemigrations
i am interested in learning Django for python. Therefore i followed their Tutorial - yet now i am stuck at the following point of the second tutorial element: Problem: According to the tutorial i shall run a "Database Migration" by using the following codes: python3 manage.py makemigrations python3 manage.py migratecode I do receive the following error message on execution of the first command (makemigrations): > (django_second_test) sebastian@sebastian-Lenovo-Y50-70 > ~/Dokumente/py_virtualenv/django_virtualenv/django_second_test/locallibrary/locallibrary > $ python3 manage.py makemigrations Traceback (most recent call last): > File "manage.py", line 15, in <module> > execute_from_command_line(sys.argv) File "/home/sebastian/Dokumente/py_virtualenv/django_virtualenv/django_second_test/lib/python3.5/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line > utility.execute() File "/home/sebastian/Dokumente/py_virtualenv/django_virtualenv/django_second_test/lib/python3.5/site-packages/django/core/management/__init__.py", line 365, in execute > self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/sebastian/Dokumente/py_virtualenv/django_virtualenv/django_second_test/lib/python3.5/site-packages/django/core/management/base.py", > line 288, in run_from_argv > self.execute(*args, **cmd_options) File "/home/sebastian/Dokumente/py_virtualenv/django_virtualenv/django_second_test/lib/python3.5/site-packages/django/core/management/base.py", > line 332, in execute > self.check() File "/home/sebastian/Dokumente/py_virtualenv/django_virtualenv/django_second_test/lib/python3.5/site-packages/django/core/management/base.py", > line 364, in check > include_deployment_checks=include_deployment_checks, File "/home/sebastian/Dokumente/py_virtualenv/django_virtualenv/django_second_test/lib/python3.5/site-packages/django/core/management/base.py", > line 351, in _run_checks > return checks.run_checks(**kwargs) File "/home/sebastian/Dokumente/py_virtualenv/django_virtualenv/django_second_test/lib/python3.5/site-packages/django/core/checks/registry.py", > line 73, in run_checks > new_errors = check(app_configs=app_configs) File "/home/sebastian/Dokumente/py_virtualenv/django_virtualenv/django_second_test/lib/python3.5/site-packages/django/core/checks/urls.py", > line 40, in check_url_namespaces_unique > all_namespaces = _load_all_namespaces(resolver) File "/home/sebastian/Dokumente/py_virtualenv/django_virtualenv/django_second_test/lib/python3.5/site-packages/django/core/checks/urls.py", > line 57, in _load_all_namespaces > url_patterns = getattr(resolver, 'url_patterns', []) File "/home/sebastian/Dokumente/py_virtualenv/django_virtualenv/django_second_test/lib/python3.5/site-packages/django/utils/functional.py", > line 36, in __get__ > res = instance.__dict__[self.name] = self.func(instance) File "/home/sebastian/Dokumente/py_virtualenv/django_virtualenv/django_second_test/lib/python3.5/site-packages/django/urls/resolvers.py", > line 536, in url_patterns > patterns = … -
django celery @app.on_after_finalize.connect called twice
Using supervisor I start command = celery worker --app project --loglevel info --concurrency 1 and command = celery beat --pidfile= --app project --loglevel info --scheduler django_celery_beat.schedulers:DatabaseScheduler In my django app in tasks.py I set up crontab schedules. e.g. @app.on_after_finalize.connect def setup_periodic_tasks(sender: Celery, **kwargs): logger.info("Setting up periodic tasks") sender.conf.timezone = 'Europe/London' schedule, _ = CrontabSchedule.objects.get_or_create( minute='45', hour='*', day_of_week='*', day_of_month='*', month_of_year='*' ) PeriodicTask.objects.filter(name='Rebuild Order Cache').delete() PeriodicTask.objects.update_or_create(crontab=schedule, name='Rebuild Order Cache', task='app.tasks.rebuild_sales_order_cache') I get the log message twice. It seems that both celery instances started with supervisor are triggering '@app.on_after_finalize.connect' What should I do to have it run only one? -
How can I pre-set some value on django form?
forms.py class UserCreateForm(forms.ModelForm): username = forms.CharField(widget=forms.TextInput(attrs={'value': 'Hello_1'})) email = forms.EmailField(widget=forms.EmailInput(attrs={'value': 'Hello_2'})) password = forms.CharField(widget=forms.PasswordInput(attrs={'value': 'Hello_3'})) class Meta: model = User fields = ['username', 'email', 'password'] views.py def create(request): form = UserCreateForm() return render(request, 'create.html', {'form': form}) In views.py Not in forms.py, How can I set some values on form's page initially render? I want to set different value depending on the type of form's fields. -
TLS issue while calling stripe charge API from my local env
I am implementing Stripe payment gateway in sandbox mode. I have embedded checkout process and also created token which is used by server to call API to create charges. API version used is: stripe.api_version = '2017-06-05' charge = stripe.Charge.create( amount=1000, currency="usd", description="Example charge", source=token, ) When I call this charge create api, I receive the following error: b'{\n "error": {\n "type": "invalid_request_error",\n "message": "Stripe no longer supports API requests made with TLS 1.0. Please initiate HTTPS connections with TLS 1.2 or later. You can learn more about this at https://stripe.com/blog/upgrading-tls."\n }\n}\n' The stripe API used to create charges in local machine is: POST: https://api.stripe.com/v1/charges How can I make it work on my local machine? But when I deployed it to AWS it is working there.