Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. with celery beat
I have a periodic task which creates and saves model every second. So i configured this CELERY_IMPORTS = ( 'myapp.tasks', ) CELERY_BEAT_SCHEDULE = { 'periodic_task': { 'task': 'myapp.tasks.periodic_task', 'schedule': timedelta(seconds=1), }, } and typical celery.py: from __future__ import absolute_import, unicode_literals import os from celery import Celery from django.conf import settings os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myapp.settings') app = Celery('myapp') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) and finally i've configured supervisord to start this: [program:myapp-celery] command=/home/me/myapp/venv/bin/celery worker -A myapp --loglevel=INFO directory=/home/me/myapp user=nobody numprocs=1 stdout_logfile=/home/me/myapp/logs/celery.log stderr_logfile=/home/me/myapp/logs/celery.log autostart=true autorestart=true startsecs=10 stopwaitsecs = 600 stopasgroup=true priority=1000 And it starts function in tasks.py which uses imported model, which as i understand is not loaded yet, causing this error django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.> So i want some hook or flag indicating that everything is set so that my schedule can start executing this periodically. -
Django: Connecting two models via save()
my project has two steps 1) database entrance for order model 2) database entrance for transaction profile. Same time 1) will be updated with the foreign key to 2) I tried to keep my view.py as clean as possible and modified the save() function. However, I have read that this is not always recommended and I wondered if you have any feedback to my approach below or if you would have done it any different. views.py def checkout_page(request): session_order_id = request.session['order_id'] if request.POST: transaction_profile = TransactionProfileModelForm(request, request.POST) if transaction_profile.is_valid(): t = transaction_profile.save(commit=False) t.save() else: transaction_profile = TransactionProfileModelForm(request) forms.py from orders.models import Order class TransactionProfileModelForm(forms.ModelForm): email_confirm = forms.EmailField() class Meta: model=TransactionProfile fields = [ 'email', 'email_confirm', 'address_line_1', 'address_line_2', 'city', 'country', 'postal_code', 'state' ] def __init__(self, request, *args, **kwargs): self.request = request super(TransactionProfileModelForm, self).__init__(*args, **kwargs) def save(self, commit=True): obj = super(TransactionProfileModelForm, self).save(commit=False) if commit: obj.save() request = self.request session_order_id = request.session['order_id'] o = Order.objects.get(order_id=session_order_id) o.transaction_profile = obj o.save() return obj -
"polls.apps.PollsConfig" and "polls" in `INSTALLED APPS'
To tell Django which apps are installed, the official documentation introduces The advantage 'polls.apps.PollsConfig' over 'polls' setting.py INSTALLED_APPS = [ #my APPs "polls.apps.PollsConfig", ] This explicitly refer to the installed app in app.py from django.apps import AppConfig class LearningLogsConfig(AppConfig): name = 'learning_logs' However, in some books, it tell it in a shortcut setting.py INSTALLED_APPS = [ #my APPs "polls", ] How Django access 'polls' in this situation? -
Django tests manage.py
To run my Django's tests, I was using the manage.py file. But I decided to create my own file runtests.py. As specified in the Django's doc, the manage.py file will execute all methods whose name is starting like "test" and whose class inherits TestCase ! My aim is to use this searching method to display all possible tests (not running them). So do you know where I could get this "searching method" ? Thank you ! -
Django models.DateTimeField and Postgres int
My class Model has following timestamp: timestamp = models.DateTimeField(default=datetime.now) It works fine with SQLLite, but changing to Postgres I am getting error: column "timestamp" is of type integer but expression is of type timestamp with time zone I want to keep my model with DateTimeField but how to convert this type required by Postgres? -
Django form.is_valid() cleans needed values
I am practicing Django, and I have been stuck on this for a while now. I am trying to write a basic survey app. My issue is that when I submit my form, I can see that request.POST contains the data I need, form.data also contains it, but after I run form.is_valid(), I am left with only the keys in the dict, no values. class SurveyForm(forms.Form): def __init__(self, *args, **kwargs): questions = kwargs.pop('questions') super(SurveyForm, self).__init__(*args, **kwargs) for q in questions: choices = [] for answer in q.choice_set.all(): choices.append((answer.pk, answer.choice_text)) self.fields[q.id] = forms.ChoiceField(label=q.question_text, required=False, choices=choices, widget=forms.RadioSelect) def answers(self): for q, a in self.cleaned_data.items(): yield self.fields[q] If I remove required=False, I keep getting This field is required although, I believe it's due to the validation, because it looks like the page refreshes when I hit submit, while if I actually leave the choices blank, it doesn't refresh and instead a small popup appears above the label. Here is the view that uses it. def step(request, survey_id, attempt_id, surveypage_nr): survey = get_object_or_404(Survey, pk=survey_id) attempt = get_object_or_404(Attempt, pk=attempt_id) pages = survey.surveypage_set.all().order_by('page_nr') page = pages.filter(page_nr=surveypage_nr).first(); questions = page.question_set.all() form = SurveyForm(request.POST or None, questions=questions) if form.is_valid(): for a in form.answers(): answer = get_object_or_404(Choice, pk=a) attempt.score … -
resp.context['user'] is always 'AnonymousUser' even after client.login
I am new to django unit testing so I referred to https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/Testing when working on it. I have been trying out a lot of solutions out there but am still unable to make my unit tests work as expected. from django.core.urlresolvers import reverse from django.test import Client, TestCase from django.contrib.auth.models import User from contacts.models import Contact, CList class ContactViewTest(TestCase): def setUp(self): self.client = Client(HTTP_HOST='localhost:8000') user = User.objects.get(id=2) password = 'password' company = user.profile.company self.user = user self.password = password def test_logged_in_all_contacts_correct_template(self): login = self.client.login(username=self.user.username, password=self.password) resp = self.client.get(reverse('all-contacts'), follow=True) # Check if user is logged in self.assertEquals(str(resp.context['user']), self.user.username) # Check if response is "success" self.assertEqual(resp.status_code, 200) self.assertTemplateUsed(resp, 'all_contacts.html') This is the error message I got from after running python manage.py test contacts.tests.test_views -k self.assertEquals(str(resp.context['user']), self.user.username) AssertionError: 'AnonymousUser' != u'xxx' -
Django - Single background task executed in parallel
By using Django Background Tasks I am doing a bulk upload process. The tasks takes a record id which has zip file location as input. As soon as task starts, it extracts contents to a folder inside django's tmp directory with directory name as current timestamp. The task takes approximately 5 minutes to complete. I am currently running only one instance of process_tasks ( python manage.py process_tasks ). But what happens is, after ~1 minute to starting, by somehow another run of same task is being triggered for same zip file and it creates a new folder with timestamp ( This is how I figured out it runs after ~1 minute) and starts processing in parallel. What is going wrong or I am missing? Thanks in advance Current solution - Currently I have added a status column to record and setting it as 'in_progress' as soon as it starts. On the next run, when the status is in_progress, its getting skipped. -
Postgresql + Django : Not Null Fields Empty Value
I know the title doesn't make any sense, but I just want to know how to insert an empty string or '' in a CharField made in Django? As far as I know by default, fields in Django are not nullable. Checking data in PGAdmin, I can see that most of the CharFields have '' as value. I wonder how is this possible? If I run cur_p.execute(""" INSERT INTO "table"name" (address, school_address, sports ) VALUES ('', '', '') I will get psycopg2.IntegrityError: null value in column "created" violates not-null constraint -
How to set session data for multiple websites in Django?
I have 3 websites, example1.com, example2.com, example3.com. If user signs in on any of the websites and if future if the same user navigates to the any of the other websites, he should be logged in. In django SESSION_COOKIE_DOMAIN in settings only limits to one domain or different subdomains. Here I don't have a choice to use subdomains. What should I do? -
patch django.conf settings does not mutate the value
I have VOUCHERED_PEOPLE in the base.py And I need to test it by dummy I have read this in order to get settings.VOUCHERED_PEOPLE being patched, but it does not work in Django2 utils.py from django.conf import settings def get_voucher_people(mobile_phone: str) -> typing.Dict[str, typing.Union[str, int]]: """Read name from base.py""" for record in settings.VOUCHERED_PEOPLE: if record['mobile_phone'] == mobile_phone: return record return None base.py VOUCHERED_PEOPLE = [{...}, {...}] tests.py with patch('poinkbackend.apps.vouchers.utils.settings', VOUCHERED_PEOPLE=dummy): from pprint import pprint import ipdb; ipdb.set_trace() give_voucher(sarit.userprofile, True) Problem: patch does not work. It is not change value to be my dummy Question: Where am I wrong? -
Django Rest Framework columns with Manytomanyfield
How to serialize data of ManyToMany field. I am having problem in saving the data in ManyToMany field. However , I have found an alternate way but what's the best way to do it. I have used it in views.py. addrole = Layer.objects.create(title=str(key), enabled=True) addrole.group.add(self.request.POST['group']) Any better way to do it ? -
heroku push master :No matching distribution found
I'm trying to push my django app to heroku but each time issue the heroku push master command i get "No matching distribution found"---for each line of dependencies in the requirements.txt file. Have tried many fix i found online but none seems to be working for me.enter image description here -
Coverting a FileField into binary then use lossless compression and decompress in django 1.11 + python3 + rest_framework
I have the following model below. How do I convert the FileField to binary and then use lossless method to compress,save it and later decompress it? class EmployeeDocument(models.Model): """ Model, Which holds Employee documents uploaded. """ employee = models.ForeignKey( Employee, related_name="employee_docs", null=True, blank=True) document = models.FileField( upload_to='Images/', default='Images/None/No-img.jpg') details = models.TextField() # url = models.URLField(null=True) # path_to_image = models.CharField(null=True, max_length=100) # upload_date = models.DateTimeField(auto_now=True, db_index=True) def __str__(self): return 'DOC - %s' % (self.employee.user.user -
django: annotate on annotated values
I have two queries q1 = A.objects.annotate(sum_p=F('field_4')).values('field_1', 'field_2', 'field_3', 'sum_p') q2 = B.objects.annotate(sum_p=F('field_4') * -1).values('field_1', 'field_2', 'field_3', 'sum_p') q3 = q1.union(q2, all=True) q6 = q3.values('field_1').annotate(sum_sum_p=Sum(F('sum_p)) * - 1) Gives keyerror: sum_p inspite of q3.query having column 'sum_p' Basically i am taking data from two Models with one value being negative and then I want to sum them i.e. annotate on annotated values. Is there any solution to this or do i need to go for raw queries Thank You in Advance -
I want to give alias name to the translation fields in django admin display
I have a field called 'name' defined in my model and registered with translation.py The fields gets stored in database as name,name_en,name_he. I want to display the fields as name_English in admin panel. How to do that? -
Django dynamic form with FileField
I am trying to generate a dynamic form using JSONField in my models.py - class FormSchema(models.Model): title = models.CharField(max_length=100) schema = JSONField(load_kwargs={'object_pairs_hook': collections.OrderedDict}) What happens is that I take the field_type to be added from the user, add it into the schema, and to display the generated form I use the following code: myform = forms.Form() for key, value in old_form.schema.items(): field_class = get_field_class_from_type(value) myform.fields[key] = field_class() Where get_field_class_from_type() is: def get_field_class_from_type(value_type): if value_type == "string": return forms.CharField elif value_type == "number": return forms.IntegerField elif value_type == "date": return forms.DateField elif value_type == "email": return forms.EmailField # elif value_type == "image": # return forms.ImageField # elif value_type == "file": # return forms.FileField else: return None The issue is that, forms.FileField does not have upload_to, and since my model doesn't have FileField (only JSONField is there), the file is not uploaded anywhere.. just sent directly. Is there any way to upload the file to a particular location like in models.FileField? -
Compressing and Decompressing on POST and GET requests using lz4 + djnago + rest_framework
I am using django 1.11 + rest_framework trying to implement lossless compression method using lz4 python library. In a nutshell,I have Implemented a class based view POST method that has the compression method defined. I would later want to implement a decompression method when a GET request is done. How do is there any other way I would implement compressing and decompressing of files on POST and GET methods? My model is as follows: class EmployeeDocument(models.Model): """ Model, Which holds Employee documents uploaded. """ employee = models.ForeignKey( Employee, related_name="employee_docs", null=True, blank=True) document = models.FileField( upload_to='Images/', default='Images/None/No-img.jpg') details = models.TextField() # url = models.URLField(null=True) # path_to_image = models.CharField(null=True, max_length=100) # upload_date = models.DateTimeField(auto_now=True, db_index=True) def __str__(self): return 'DOC - %s' % (self.employee.user.username) Then Views.py class EmployeeDocumentPOST(APIView): """ compress Document """ permission_class = [AllowAny] serializer_class = EmployeeDocumentSerializer def compressed_doc(self,document): document = lz4.frame.compress(document) return document def post(self, request, *args, **kwargs): compressd_doc = self.compressed_doc(document) employee = Employee.objects.get(id=request.data.pop('employee')) detail = request.data.get('detail') employee_doc = EmployeeDocument.objects.create(**request.data) employee_doc.compressed_doc = compressed_doc employee_doc.employee = employee employee_doc.detail = detail employee_doc.save() serializer = EmployeeDocument(employee_doc) return Response(serializer.data, status = status, status = status.HTTP_200_OK) -
Django: Update model with new foreign_key
I created a form with the model form manager. Before saving my TransactionProfile ModelForm, I want to connect it with an order model. When I print session_order_id it is the correct id, however self.order_set.get is always empty when I print it in the console. Anyone can help me with that? Would you in general solve it the way I did it here, or ist there a more clean method? In my views.py I have the following: t = transaction_profile.save(commit=False) t.update_order_with_transaction_profile(session_order_id) t.save() My models.py has the following code: def update_order_with_transaction_profile(self, session_order_id): # In ModelManager or just in class TransactionProfile o = self.order_set.get(order_id=session_order_id) o.transaction_profile = self o.save() -
Autopcalculate value in Django formset field
I'm using Django formset to allow user to enter stock details for the user in multiple rows at once.I have the price and quantity entered by the user in each row.i need to multiply this values and show in the last column for each row when user enter the value. i tried to write the javascript as below which will work fine for first row.How can i make it apply for the entire table function update() { document.getElementById("id_form-0-price").value = document.getElementById("id_form-0-quantity").value*document.getElementById("id_form-0-unitprice").value; } In the field name 'id_form-0-price' , 0 is the prefix set by formset,which is hardcoded in this case.i want to make the above script run for any row in the table.Any suggestions? -
Storing calculations for computed columns in the database
I am building a web app in Django. In this app there is a model where some properties are calculated based on other properties of this model. I could program the properties in the source code but I want the user to define the calculations (and maybe also additional properties and their calculation). Which would mean I'd want to store the calculation in the database and use something like eval to process it. That means simply one row with a string as the calculation. But then I would need to build a ton of security checks to prevent any arbitrary code from executing. Or I could need to build my own programming language that would compile to Python. Another option would be to define all the options in the database. So a table with operators, a table with properties and a table about combining those into a calculation. Which sounds terribly complicated and heavy on the database since I would need to query that a lot. I feel like this is a problem that has been solved before, what is a good solution? -
Architecting an eCommerce Platform using Django-Oscar Framework
I am looking to architect an eCommerce platform on Django-Oscar framework. I would like some opinions on the best way to move forward. Here are some of my ideas... Take a SOA three server approach. Server 1 is a authentication and presentation layer. This is built on Django framework. Only utilises Templates and Views (not Models) from the Django framework. Instead of Models, accesses data server via API calls. Also this layer authenticates the user using the Django authentication framework. Server 2 is the data layer. Built on Django REST Framework where views expose data models via REST API. Server 3 is the business logic, that is the eCommerce platform. Built on Django-Oscar-API framework where views expose business logic via REST API. So only Server 1 is exposed externally. What is the best way to pass on the authentication between the internal servers. Would JWT authentication be a good option? Is there another better approach? Overall, is this a good approach given that the data layer will server both the presentation layer as well as the business layer? -
Django Json post request Payload error
Hi I am accessing an url with payload. I tried this code for payload: app_id = "Dert/dedff/12i=" payload = "{\n \"app_id\": \"{}\"\n}".format(app_id) When do request, Django give following error. Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 1.10.4 Exception Type: KeyError Exception Value: 'app_id' -
How can I display the contents of a related table within the Django admin change form?
I'm new to programming, Python, and Django, so your patience is appreciated. I have been writing a practice application in Django for storing cooking recipes. I have two models: class Recipe(models.Model): recipe_name = models.CharField(max_length=30) recipe_instructions = models.TextField() recipe_whyitworks = models.TextField(verbose_name="Why It Works") recipe_date = models.DateField() def __str__(self): return self.recipe_name def was_published_recently(self): return self.recipe_date >= timezone.now() -datetime.timedelta(days=5) class Ingredient(models.Model): recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE) ingredient_name = models.CharField(max_length=30) ingredient_qty = models.DecimalField(verbose_name='Quantity', max_digits=3, decimal_places=2) ingredient_uom = models.CharField(verbose_name='Unit of Measure', max_length=15) def __str__(self): return self.ingredient_name I have admin set to be able to edit either table: from django.contrib import admin # Register your models here. from .models import Recipe, Ingredient admin.site.register(Recipe) admin.site.register(Ingredient) What I want to do is when I click on an "Ingredient" I would like it to show all previous ingredients added to the recipe, along with the quantity and unit of measure for each in a table, in addition to the fields which allow me to add a new one. Thanks in advance for your help! -
The leading underscore in `description = _("Small integer")`
There's code in /django/db/models/fields/init.py class SmallIntegerField(IntegerField): description = _("Small integer") def get_internal_type(self): return "SmallIntegerField" When I tried: In [1]: description = _("Small integer") TypeError: 'str' object is not callable What's the underscore here which leads the tuple?