Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
First Django cron with Celery
I read lot of documentations about Celery with Django and I tried to create my first cron task. Objective : This task should be able to execute a function which clean a specific table each day at 11:30 am My code : All seems to be good, I see the task in Celery but nothing change. I have in my base.py file : INSTALLED_APPS = ( .... 'django_cron', ) CRON_CLASSES = [ "ocabr.cron.cron.DeleteOldToken", ] CELERY_BROKER_URL = 'redis://localhost:6379' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_RESULT_BACKEND = 'redis://localhost:6379' CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_IGNORE_RESULT = False CELERY_TASK_TRACK_STARTED = True # Add a one-minute timeout to all Celery tasks. CELERYD_TASK_SOFT_TIME_LIMIT = 60 I have a celery.py file : import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'main.settings.base') app = Celery('main') app.config_from_object('django.conf:settings', namespace='CELERY') # Load task modules from all registered Django app configs. app.autodiscover_tasks() I have a cron.py file : # -*- coding: utf-8 -*- from django_cron import CronJobBase, Schedule from ..tasks import delete_old_token class DeleteOldToken(CronJobBase): RUN_AT_TIMES = ['11:30'] schedule = Schedule(run_at_times=RUN_AT_TIMES) code = 'ocabr.delete_old_token' def do(self): delete_old_token() And the file tasks.py : # -*- coding: utf-8 -*- import datetime from datetime import datetime from celery import shared_task, task from dateutil.relativedelta import relativedelta from django.conf import settings … -
How to pass context from two tables for django-filters
How to pass model for listview which is the result of left join with two tables ? I have a class based view where the model is class Contact. Every contact can be my favourite and this info is saved in class Favourite. I need to pass model to view which consists of all contacts and information about is this contact favourite or not. How can I pass it to the view? Thanks for answers. ///Fave model class Fave(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='user_faves') content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') fave = models.BooleanField(default=True) def get_absolute_url(self): return reverse('contact:favorite') ///Contact model class Contact(models.Model): COMPANY = 'C' PERSON = 'P' TYPE_CHOICES = ( (COMPANY, 'Company'), (PERSON, 'Person'), ) name = models.CharField(max_length=255, blank=True) type = models.CharField(max_length=1, blank=False, choices=TYPE_CHOICES) country = models.CharField(max_length=128, blank=True) state = models.CharField(max_length=128, blank=True) city = models.CharField(max_length=128, blank=True) faves = GenericRelation(Fave, related_query_name='faves') notes = GenericRelation(Note, related_query_name='notes') def __str__(self): return self.name def get_absolute_url(self): return reverse('contact:contact_detail') ///CBV class ContactListView(LoginRequiredMixin, ListView): """View list of companies""" model = Contact template_name = 'contact/contact_list' context_object_name = 'contacts' def get_context_data(self, **kwargs): """TODO faves """ context = super().get_context_data(**kwargs) context['filter'] = ContactFilter(self.request.GET, queryset=self.get_queryset()) return context -
Multiplying the values of two objects in Django Models
Hey I'm working with one Django Project, where i wanted to multiply the values of two different objects in django model and storing it to the database. Here is My code of model from django.db import models from django.utils import timezone from master.models import Supplier class RawItem(models.Model): item_code = models.AutoField(primary_key=True) item_name = models.CharField(max_length=100) item_price = models.PositiveIntegerField() item_Description = models.TextField() def __str__(self): return self.item_name class PurchaseOrder(models.Model): raw_item = models.ForeignKey(RawItem, on_delete=models.CASCADE) quantity = models.PositiveIntegerField() total_prize = models.PositiveIntegerField(editable=False, blank=True, null=True) po_date = models.DateTimeField(default=timezone.now) supplier = models.ForeignKey(Supplier, on_delete=models.CASCADE) def save(self, *args, **kwargs): total_prize = self.raw_item.item_price * self.quantity super(PurchaseOrder, self).save(*args, **kwargs) so here i wanted to multiply item_price with quantity how to do that thank you in advance -
Django won't run on Apache with mod_wsgi
I'm trying to get Django 2.2 to run on Apache 2.4 with Python 3.7 on a Windows 2016 Server. Django runs fine on the development server (manage.py runserver) and the Apache Server runs and is reachable on the network but Django doesn't run on Apache. This is the Apache config (httpd.conf) I'm running: ServerName localhost:80 <Directory /> AllowOverride none Require all denied </Directory> LoadFile "c:/program files/python37/python37.dll" LoadModule wsgi_module "c:/program files/python37/lib/site-packages/mod_wsgi/server/mod_wsgi.cp37-win_amd64.pyd" WSGIPythonHome "c:/program files/python37" WSGIScriptAlias \ "D:\Django\myproject\myproject\wsgi.py" WSGIPythonPath "D:\Django\myproject\myproject" <Directory "D:\Django\myproject\myproject"> <Files wsgi.py> Require all granted </Files> </Directory> DocumentRoot "${SRVROOT}/htdocs" <Directory "${SRVROOT}/htdocs"> Options Indexes FollowSymLinks AllowOverride None Require all granted </Directory> <IfModule dir_module> DirectoryIndex index.html </IfModule> Here's my wsgi.py (not changed from what was generated during manage.py startproject): import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings') application = get_wsgi_application() When I try to load http://myserver in the browser, I get the Apache Defualt page, but If I try to load http://myserver:8000 I get a connection error. -
Django oscar cannot change Urls
I have setup a django oscar project and i'm trying to configure urls. Goal is to change catalogue to catalog. As per the documentation i've added app.py in myproject/app.py myproject/app.py from django.conf.urls import url, include from oscar import app class MyShop(app.Shop): # Override get_urls method def get_urls(self): urlpatterns = [ url(r'^catalog/', include(self.catalogue_app.urls)), # all the remaining URLs, removed for simplicity # ... ] return urlpatterns application = MyShop() myproject/urls.py from django.conf.urls import url, include from django.contrib import admin from . import views from .app import application urlpatterns = [ url(r'^i18n/', include('django.conf.urls.i18n')), url(r'^admin/', admin.site.urls), url(r'', application.urls), url(r'^index/$',views.index, name = 'index'), ] The project server runs without any error. but when i try localhost:8000/catalog i get NoReverseMatch at /catalog/ 'customer' is not a registered namespace. The expected output is localhost:8000/catalog should return the catalogue page. -
How to display file&folder tree with Django APP
I really need help. I’ve got SQL table which contains exhaustive files and folders information and I need to show tree of those files on a website. But not only show, it’s supposed to be interactive, so that a user can scroll, open folders and mark any of the items. I think it might look like this https://yadi.sk/i/H3wzUMt_UmT3AQ. If someone can give advice how to implement this app in django that would be really helpful, or maybe just any thoughts regarding it, I’d really appreciate it. -
how to get json text inside select in django-admin
So i already create my json file, and it is woriking fine, when i go to my browser and put rua/list/?freguesia_id=10001 it already show the name of rua that belong to freguesia with id = 10001 https://i.stack.imgur.com/3oSoT.png Now i want to get my nome of ruas and when i select freguesia will show tha names of ruas in another select. https://i.stack.imgur.com/t3m1u.png i want to do it in javascript , and i am working on django-admin, and i am little lost here. JAVASCRIPT (function($) { // Get my fregusia $("#freguesia").change(function (){ var freguesiaId = $("#freguesia"); var url = // what's my url to fetch my json $.getJSON(url, function(data) { var rua = // How do I convert my text into this variable? } }); }) HTML {% extends 'admin/change_form.html' %} {% load static %} {% block admin_change_form_document_ready %} {{ block.super }} <script src='{% static "daa/avarias/admin/js/example.js" %}'></script> {% endblock %} URLS.PY urlpatterns = [ path('rua/list/', get_ruas, name='get_ruas'), ] -
Django: append manual queryset to queryset object
I'm using Django 1.5. I have a table MultiUser class MultiUser(models.Model): user = models.ForeignKey(User, related_name='owner_user') shared_user = models.ForeignKey(User, related_name='shared_user') access_level = models.CharField( default='Viewer', max_length='100', blank=True ) This table maps users with access level under owner user. user field defines the owner user and shared_user is the mapped user who can be either manager or viewer I have defined a model manager method to get list of all users including the owner user. def getSharedUsers(self, user): # Get owner owner = None if self.filter(user=user).exists(): owner = user elif self.filter(shared_user=user).exists(): owner = self.filter(shared_user=user)[0] # Get all users shared_users = [] if owner: shared_users = self.filter(user=owner) shared_users.append({ 'shared_user': owner, 'access_level': 'OWNER', 'created': owner.created }) return shared_users Since owner user has no access_level defined in the MultiUser model. I want to manually append the owner user to the queryset list with shared_user field set to the owner user and access_level as owner. But this gives error as 'QuerySet' object has no attribute 'append' It is possible to append manually generated object to the queryset object? If yes how? -
Python 3.5 weakref.py TypeError: 'NoneType' object is not callable Error
I have django project in python 3.5 and django 2.1.5 When ever i hit requirement.txt or install any new package. I got this error Exception ignored in: <function WeakValueDictionary.__init__.<locals>.remove at 0x7f5400eafbf8> Traceback (most recent call last): /home/ubuntu/.virtualenvs/myproject/lib/python3.5/weakref.py", line 117, in remove TypeError: 'NoneType' object is not callable Exception ignored in: <function WeakValueDictionary.__init__.<locals>.remove at 0x7f5400eafbf8> Traceback (most recent call last): File "/home/ubuntu/.virtualenvs/myproject/lib/python3.5/weakref.py", line 117, in remove TypeError: 'NoneType' object is not callable Although it don't affect my code anyway, but why is this error occaring -
Display message button on other users' profile
I would like to display a message button on other users' profile but not on my profile after I login in a Django website. I can check the user authentication by {% if user.is_authenticated %} But how to check if the user is not the one on the profile and then display the message button? Thanks in advance! -
success message is not working with create view
I have used SuccessMessageMixin class but then also in the createview i didnot get the success message but in the updateview it is working when i return the super().form_valid(form) class DepartmentCreateView(LoginRequiredMixin, PermissionRequiredMixin,SuccessMessageMixin ,CreateView): template_name = 'departments/create_department.html' form_class = DepartmentForm success_url = reverse_lazy('departments:departments') permission_required = ('departments.add_department',) def form_valid(self, form): department = form.save(commit=False) department.slug = slugify(uuid.uuid4()) department.save() return super().form_valid(form) -
Postgres query: Abnormal Disk I/O
My production query suffers of a strange I/O hit, i can't figure out where is the problem, i mean, it's a simple query without any massive join or something like that... My table has around 300K of rows, and grows like 15/20K row per day, here is the table definition: CREATE TABLE public.tv_smartdevicemeasurement_modbus ( measurement_id integer NOT NULL DEFAULT nextval('tv_smartdevicemeasurement_modbus_measurement_id_seq'::regclass), insert_time timestamp with time zone NOT NULL, data jsonb NOT NULL, parent_job_id integer NOT NULL, smart_device_id integer NOT NULL, CONSTRAINT tv_smartdevicemeasurement_modbus_pkey PRIMARY KEY (measurement_id), CONSTRAINT tv_smartdevicemeasur_parent_job_id_1ac4609e_fk_tv_measur FOREIGN KEY (parent_job_id) REFERENCES public.tv_measurementjobs (job_id) MATCH SIMPLE ON UPDATE NO ACTION ON DELETE NO ACTION DEFERRABLE INITIALLY DEFERRED, CONSTRAINT tv_smartdevicemeasur_smart_device_id_62c12ed0_fk_tv_smartd FOREIGN KEY (smart_device_id) REFERENCES public.tv_smartdevice_modbus (device_id) MATCH SIMPLE ON UPDATE NO ACTION ON DELETE NO ACTION DEFERRABLE INITIALLY DEFERRED ) WITH ( OIDS = FALSE ) TABLESPACE pg_default; CREATE INDEX tv_smartdevicemeasurement_modbus_parent_job_id_1ac4609e ON public.tv_smartdevicemeasurement_modbus USING btree (parent_job_id) TABLESPACE pg_default; CREATE INDEX tv_smartdevicemeasurement_modbus_smart_device_id_62c12ed0 ON public.tv_smartdevicemeasurement_modbus USING btree (smart_device_id) TABLESPACE pg_default; Here is the query: EXPLAIN (ANALYZE, BUFFERS) SELECT "tv_smartdevicemeasurement_modbus"."measurement_id", "tv_smartdevicemeasurement_modbus"."smart_device_id", "tv_smartdevicemeasurement_modbus"."parent_job_id", "tv_smartdevicemeasurement_modbus"."insert_time", "tv_smartdevicemeasurement_modbus"."data", (SELECT DATA->> 'VLN_AVG') AS "VLN_AVG", (SELECT DATA->> 'VLN3') AS "VLN3", (SELECT DATA->> 'VLN2') AS "VLN2", (SELECT DATA->> 'VLN1') AS "VLN1", (SELECT DATA->> 'VL1-2') AS "VL1-2", (SELECT DATA->> 'VL2-3') AS "VL2-3", (SELECT DATA->> … -
how can i save an image for any user
In my website user can upload a image to edit it so i should save his image in model and to access again to image i should save username of user for any image. but i have a problem. I want when user go to home page his image be deleted. But i have problem. This error: OperationalError at / no such column: imgProcess_image.username # model class Image(models.Model): username = models.CharField(unique=True, max_length=30) image = models.ImageField(upload_to='user_images') # form class Upload(forms.ModelForm): username = Image.username class Meta: model = Image fields = ['image'] def set_user(self, un): self.username = un # views def delete_image(request): Image.objects.get(username=request.user.username).delete() def home(request): delete_image_of_user(request) hash = {} comments = CommentModel.objects.all() hash["comments"] = comments return render(request, "imgProcess/home.html", hash) -
Redirecting to Login page to whatever link i click on
Whatever the link i click on it i redirecting to login page only. I have tried changing urls.py order and redirecting the urls but i want signup should redirect to the signup page and login should redirect it to the login page.but when i am clicking on any link it is redirecting to login page only. urls.py ------ from django.contrib import admin from django.urls import path from django.conf.urls import url from app import views from django.contrib.auth import views as auth_views from django.contrib.auth.views import LoginView from django.contrib.auth.views import LogoutView from django.views.generic.base import TemplateView from django.conf.urls import url, include app_name = "App" urlpatterns = [ url(r'^index/', views.index,name='index'), url(r'^signup/', views.signup,name='signup'), url(r'^Login/', views.Login,name='Login'), url(r'^Logout/', views.Logout,name='Logout'), url('admin/', admin.site.urls), url('App/', include('django.contrib.auth.urls')), url('', TemplateView.as_view(template_name='home.html'), name='home'), ] models.py: --------- from django.db import models from django.template.defaultfilters import slugify from django.contrib.auth.models import User class Event(models.Model): fname = models.CharField('fname', max_length=120) lname = models.CharField('lname',max_length=120) username = models.CharField('username',max_length = 60,unique=True) password = models.CharField('password',max_length=120,default='pavi@2789') def __unicode__(self): return self.fname class Meta: # managed = False db_table = "user" view.py: --------- from django.contrib.auth.forms import UserCreationForm from django.shortcuts import render, redirect from django.contrib.auth.models import User from django.contrib.auth import authenticate, logout,login from django.http import HttpResponse, HttpResponseRedirect from django import forms from .forms import UserRegistrationForm from .models import Event … -
How to use different db tables for a Django model based on the datetime provided in the queries?
Problem: I have a model, say Location, which has huge amount of rows and any query for this model takes unreasonable amount of time to complete. I was thinking of using a new table for this model which will enable my app to store future entries to this new table. Also, when the app queries for old data using created column, it compares to a hard-coded datetime value in the model and decides which table to use for the query. Is it possible to setup a model for such use case? 1. Location.objects.create(lat='zzzz', lng='zzzzz') <-- Uses new table 2. Location.objects.filter(created__date__gte=zz-zz-zzzz) <-- Uses old table I understand that, for 2nd line of code, I won't get the data stored in the new table. -
Django: Does select_for_update lock rows from subqueries?
Software: Django 2.1.0, Python 3.7.1, MariaDB 10.3.8, Linux Ubuntu 18LTS We recently added some load to a new application, and starting observing lots of deadlocks. After a lot digging, I found out that the Django select_for_update query resulted in an SQL with several subqueries (3 or 4). In all deadlocks I've seeen so far, at least one of the transactions involves this SQL with multiple subqueries. my question is... Does the select_for_udpate lock records from every table involved? In my case, would record from the main SELECT, and from other tables used by subqueries get locked? Or only records from the main SELECT? From Django docs: By default, select_for_update() locks all rows that are selected by the query. For example, rows of related objects specified in select_related() are locked in addition to rows of the queryset’s model. However, I'm not using select_related() , at least I don't put it explicitly. Summary of my app: with transaction.atomic(): ModelName.objects.select_for_update().filter(...) ... update record that is locked ... 50+ clients sending queries to the database concurrently Some of those queries ask for the same record. Meaning different transactions will run the same SQL at the same time. After a lot of reading, I did … -
pyfpdf write_html In-line CSS style attribute not working in fpdf python
I am trying to create a PDF file by using pyfpdf in python Django. the following code snippet I am trying to generate the pdf of HTML code and I am using the in-line CSS, but it not rendering the css style from fpdf import FPDF, HTMLMixin import os class WriteHtmlPDF(FPDF, HTMLMixin): pass pdf = WriteHtmlPDF() # First page pdf.add_page() html = f"""<h3>xxxxx</h3> <div style="border:1px solid #000"> <table border="1" cellpadding="5" cellspacing="0"> <tr><th width=20 align="left">xxxxxxxx:</th><td width="100">xxxxxxxx</td></tr> <tr><th width=20 align="left">xxxxxxxx:</th><td width="100">xxxxxxxxx</td></tr> <tr><th width=20 align="left">xxxxxxxx:</th><td width="100">xxxxxxxxx</td></tr> <tr><th width=20 align="left">xxxxxxxx:</th><td width="100">xxxxxxxxx</td></tr> </table> </div> <div style="border: 1px solid; padding: 2px; font-size: 12px;"> <table> <tr> <td width="20">xxxxxx: 1</td> <td width="20">xxxxxx: 0</td> <td width="20">xxxxxx: 1</td> </tr> </table> </div>""" PDF file get generated but without the CSS styling. -
How to remove Required Attribute From Django Form
I want to remove required attribute from HTML Form. And it should give error from server side that this field is required. Previously i was using required self.fields['group_name'].required=False. But it is not giving error for blank or null data. Then i came to know use_required_attribute, but i don't know about it and how to use it. class GroupForm(forms.ModelForm): use_required_attribute = False class Meta: model = Groups fields = ['group_name', 'group_description', 'group_status'] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) -
How can I get the 'id' in `get_context_data` from CBV?
I'm kinda confused since I had to override get_context_data method in order to use a template context. urls.py re_path( r"^post/(?P<id>\d+)/$",PostView.as_view(template_name="pages/post.html"), name="post", ), views.py class PostView(TemplateView): template_name = 'djangoapp/pages/post.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['dataC'] = get_object_or_404(Content, Título_id="2") return context -
Django serializer can't post or list user details
Im just new to Django RestApi, I've been migrating REST api from Java REST. So in this,i knew i would stuck upon Django methods and it's structure. Moreover to say it's super REST API far from JAVA. Model.py class class User(models.Model): name = models.CharField(max_length=255) date_created = models.DateTimeField(auto_now_add=True) date_modiefied = models.DateTimeField(auto_now=True) area = models.CharField(max_length=255) class LocationData(models.Model): user = models.ForeignKey( User, related_name='user', on_delete=models.DO_NOTHING) source_id = models.CharField(max_length=255) latitude = models.CharField(max_length=255) longitude = models.CharField(max_length=255) speed = models.CharField(max_length=255) kms = models.CharField(max_length=255) date_created = models.DateTimeField(auto_now=True) date_modiefied = models.DateTimeField(auto_now=True) area = models.CharField(max_length=255) serializer.py class class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = ('id', 'name', 'area') class LocationDataSerializer(serializers.ModelSerializer): class Meta: model = LocationData fields = ('id','source_id', 'latitude', 'longitude', 'kms', 'speed', 'user') All are fine, expect when i try to save the LocationData from there i have to provide user (ForeignKey) in order to save the LocationData. However i can't list the user details in the list, only it's shows user:1 meaning it shows the id only. If i introduce the below class LocationDataSerializer(serializers.ModelSerializer): user = UserSerailzer(many=False,read_only=True) class Meta: model = LocationData fields = ('id','source_id', 'latitude', 'longitude', 'kms', 'speed', 'user') Now the, user details can be shown, and i can't select the User object anymore! to save the … -
AttributeError: module 'importlib._bootstrap' has no attribute 'SourceFileLoader'
Im new to programming, so I have met this trouble. I ve upgraded my pip and then used pip list, ipython notebook, jupyter notebook to use anaconda, so after all this commands I got one answer : Traceback (most recent call last): File "/home/bakhytgul/anaconda3/bin/pip", line 7, in from pip._internal import main File "/home/bakhytgul/anaconda3/lib/python3.6/site-packages/pip/_internal/init.py", line 40, in from pip._internal.cli.autocompletion import autocomplete File "/home/bakhytgul/anaconda3/lib/python3.6/site-packages/pip/_internal/cli/autocompletion.py", line 8, in from pip._internal.cli.main_parser import create_main_parser File "/home/bakhytgul/anaconda3/lib/python3.6/site-packages/pip/_internal/cli/main_parser.py", line 12, in from pip._internal.commands import ( File "/home/bakhytgul/anaconda3/lib/python3.6/site-packages/pip/_internal/commands/init.py", line 6, in from pip._internal.commands.completion import CompletionCommand File "/home/bakhytgul/anaconda3/lib/python3.6/site-packages/pip/_internal/commands/completion.py", line 6, in from pip._internal.cli.base_command import Command File "/home/bakhytgul/anaconda3/lib/python3.6/site-packages/pip/_internal/cli/base_command.py", line 19, in from pip._internal.download import PipSession File "/home/bakhytgul/anaconda3/lib/python3.6/site-packages/pip/_internal/download.py", line 15, in from pip._vendor import requests, six, urllib3 File "/home/bakhytgul/anaconda3/lib/python3.6/site-packages/pip/_vendor/requests/init.py", line 97, in from pip._vendor.urllib3.contrib import pyopenssl File "/home/bakhytgul/anaconda3/lib/python3.6/site-packages/pip/_vendor/urllib3/contrib/pyopenssl.py", line 46, in import OpenSSL.SSL File "/home/bakhytgul/anaconda3/lib/python3.6/site-packages/OpenSSL/init.py", line 8, in from OpenSSL import rand, crypto, SSL File "/home/bakhytgul/anaconda3/lib/python3.6/site-packages/OpenSSL/crypto.py", line 13, in from cryptography.hazmat.primitives.asymmetric import dsa, rsa File "/home/bakhytgul/anaconda3/lib/python3.6/site-packages/cryptography/hazmat/primitives/asymmetric/rsa.py", line 14, in from cryptography.hazmat.backends.interfaces import RSABackend File "/home/bakhytgul/anaconda3/lib/python3.6/site-packages/cryptography/hazmat/backends/init.py", line 7, in import pkg_resources File "/home/bakhytgul/anaconda3/lib/python3.6/site-packages/pkg_resources.py", line 1435, in register_loader_type(importlib_bootstrap.SourceFileLoader, DefaultProvider) AttributeError: module 'importlib._bootstrap' has no attribute 'SourceFileLoader' Can u help me to solve this issue, please? Thank u very much. Im using: - Ubuntu … -
Move Nested dictionary element to top level and have remaining nested elements values follow | Python | Django
I have a dictionary, taken from a JSON file, where all of the values, including the nested values are sequential. Regardless of nesting. Obj = [{ "Text": 1, "Content": [{"Text": 2},{"Text": 3},{"Text": 4},{"Text": 5}]}, { "Text": 6, "Content": [{"Text": 7},{"Text": 8},{"Text": 9},{"Text": 10}]} ] I need to make {"Text": 3} a top-level element and move all the following elements in that nested list beneath it, like this: Obj = [{ "Text": 1, "Content": [{"Text": 2}]}, { "Text": 3, "Content": [{"Text": 4},{"Text": 5}]}, { "Text": 6, "Content": [{"Text": 7},{"Text": 8},{"Text": 9},{"Text": 10}]} ] Assuming, this list is really long, with a varying number of top-level and nested elements How would I do this efficiently? Here is a very simplified version of my actual code, the result is roughly the same I either get empty 'Content' values or, with other (much longer) variations of this code, the order of the elements gets all out of sync: Obj = [{ "Text": 1, "Content": [{"Text": 2},{"Text": 3},{"Text": 4},{"Text": 5}]}, { "Text": 6, "Content": [{"Text": 7},{"Text": 8},{"Text": 9},{"Text": 10}]} ] print(Obj) NewObj = [] lineCounter = -1 topLevelKey = -1 ElementToMove = 3 for toplevel in Obj: topLevelKey += 1 NewObj.append(toplevel) NewObj[len(NewObj)-1]['Content'] = [] for … -
Setting DateField Default value in Django Rest Framework serializer
I have a serializer with datefield which needs to be set to a default date of three days from today. I'm unable to set it using "default" argument of the datefield in the serializer. Any kind of help would be highly appreciated. -
how to activate my virtual environment in venv in flask or in django?
While installing venv in windows machine it is throwing an error: source venv/bin/activate 'source' is not recognized as an internal or external command, operable program or batch file. -
Heroku crashed: at=error code=H10 desc="App crashed" method=GET path="/"
I'm deploying my Django project on Heroku but I kept getting this Application error An error occurred in the application and your page could not be served. If you are the application owner, check your logs for details. You can do this from the Heroku CLI with the command error after typing heroku open. crashed log 2019-02-08T05:11:47.595848+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=**.herokuapp.com request_id=754cd442-2b92-4d35-ab73-f6f3f4b47dd2 fwd="144.214.90.65" dyno= connect= service= status=503 bytes= protocol=https 2019-02-08T05:11:48.592697+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=**.herokuapp.com request_id=1dfcc7fa-e278-42be-b02a-0df04c824b57 fwd="144.214.90.65" dyno= connect= service= status=503 bytes= protocol=https heroku logs --tail 2019-02-08T04:25:27.848612+00:00 app[api]: Release v1 created by user ***@gmail.com 2019-02-08T05:10:08.937759+00:00 heroku[web.1]: State changed from starting to crashed 2019-02-08T05:21:19.195680+00:00 heroku[web.1]: State changed from crashed to starting 2019-02-08T05:27:16.830898+00:00 heroku[web.1]: Starting process with command `gunicorn gettingstarted.wsgi --log-file -` 2019-02-08T05:27:19.380582+00:00 heroku[web.1]: State changed from starting to crashed 2019-02-08T05:27:19.363391+00:00 heroku[web.1]: Process exited with status 3 2019-02-08T05:27:19.253888+00:00 app[web.1]: [2019-02-08 05:27:19 +0000] [4] [INFO] Starting gunicorn 19.9.0 2019-02-08T05:27:19.254420+00:00 app[web.1]: [2019-02-08 05:27:19 +0000] [4] [INFO] Listening at: http://0.0.0.0:4868 (4) 2019-02-08T05:27:19.254514+00:00 app[web.1]: [2019-02-08 05:27:19 +0000] [4] [INFO] Using worker: sync 2019-02-08T05:27:19.258397+00:00 app[web.1]: [2019-02-08 05:27:19 +0000] [10] [INFO] Booting worker with pid: 10 2019-02-08T05:27:19.262923+00:00 app[web.1]: [2019-02-08 05:27:19 +0000] [10] [ERROR] Exception in worker process 2019-02-08T05:27:19.262927+00:00 app[web.1]: Traceback (most …