Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
POSTMAN Curd ClassbasedView
Django Postman Curd Serializer Getting Null Value while creating a student in POSTMAN models.py from django.db import models class Student(models.Model): GENDERS = ( ('f','Female'), ('m','Male') ) name = models.CharField(max_length=100) roll = models.IntegerField(unique = True) email = models.EmailField(max_length=100) gender = models.CharField(max_length=1, choices = GENDERS) percentage = models.FloatField() institute = models.ForeignKey('Institute',on_delete = models.CASCADE, null=True, blank=True) def __str__(self): return self.name class Institute(models.Model): TYPES = ( ('h', 'HighSchool'), ('c','College') ) name = models.CharField(max_length=200) type_of_institute = models.CharField(max_length=1, choices= TYPES) def __str__(self): return self.name My doubt is after creating a student in the postman after giving the value for institute i am getting null. why i am getting a null though i am giving the value for it Please click on the image for more details about error [checkmark]:https://i.stack.imgur.com/DLZ4H.jpg -
ModuleNotFoundError: No module named (projectname.appname)
models.py from django.db import models class Dhiraj(models.Model): name=models.CharField(max_length=100) email=models.EmailField(max_length=100) password=models.CharField(max_length=100) forms.py from django.forms import fields from .models import Dhiraj class StudentRegistation(forms.ModelForm): class Meta: models=Dhiraj fields=['name','email','password'] admin.py from django.contrib import admin from .models import Dhiraj @admin.register(Dhiraj) class DhirajAdmin(admin.ModelAdmin): list_display=('id','name','email','password') views.py from crudproject1.enroll.forms import StudentRegistation from django.shortcuts import render from .forms import StudentRegistation def add_show(request): if request.method=='POST': fm=StudentRegistation(request.post) else: fm=StudentRegistation(request.post) context={ 'fm':fm } return render(request,'enroll/addandshow.html') urls.py from django.contrib import admin from django.urls import path from enroll import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.add_show, name="addandshow") ] error message Exception in thread django-main-thread: File "C:\Users\Dhiraj Subedi\Desktop\dhiraj\crudproject1\crudproject1\urls.py", line 18, in from enroll import views File "C:\Users\Dhiraj Subedi\Desktop\dhiraj\crudproject1\enroll\views.py", line 1, in from crudproject1.enroll.forms import StudentRegistation ModuleNotFoundError: No module named 'crudproject1.enroll' I am creating a Django application and I am facing this issue can you please help ` -
Getting 403 Forbidden when trying to upload file to AWS S3 with presigned post using Boto3 (Django + Javascript)
I've tried researching other threads here on SO and other forums, but still can't overcome this issue. I'm generating a presigned post to S3 and trying to upload a file to it using these headers, but getting a 403: Forbidden. Permissions The IAM user loaded in with Boto3 has permissions to list, read and write to S3. CORS CORS from all origins and all headers are allowed The code The code is based on Python in Django as well as Javascript. This is the logic: First the file is retrieved from the HTML, and used to call a function for retrieving the signed URL. (function () { document.getElementById("file-input").onchange = function () { let files = document.getElementById("file-input").files; let file = files[0]; Object.defineProperty(file, "name", { writeable: true, value: `${uuidv4()}.pdf` }) if (!file) { return alert("No file selected"); } getSignedRequest(file); } })(); Then a GET request is sent to retrieve the signed URL, using a Django view (described in the next section after this one) function getSignedRequest(file) { var xhr = new XMLHttpRequest(); xhr.open("GET", "/sign_s3?file_name=" + file.name + "&file_type=" + file.type) xhr.onreadystatechange = function () { if (xhr.readyState === 4) { if (xhr.status === 200) { let response = JSON.parse(xhr.responseText) uploadFile(file, response.data, response.url) … -
Stripe Error on request.META["HTTP_STRIPE_SIGNATURE"]
I'm using Django and implemented my payments with Stripe the server shows Traceback (most recent call last): File "/home/ali/.local/lib/python3.7/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/home/ali/.local/lib/python3.7/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/ali/.local/lib/python3.7/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/home/ali/digitalstore/payment/views.py", line 120, in stripe_webhook sig_header = request.META["HTTP_STRIPE_SIGNATURE"] KeyError: 'HTTP_STRIPE_SIGNATURE' which using request.META.get("HTTP_STRIPE_SIGNATURE") cause the Unable to extract timestamp and signatures from header error on server it's my stripe_webhook @csrf_exempt def stripe_webhook(request): payload = request.body # payload = request.body.decode("utf-8") sig_header = request.META["HTTP_STRIPE_SIGNATURE"] event = None try: event = stripe.Webhook.construct_event(payload, sig_header, settings.STRIPE_WEBHOOK_SECRET) except ValueError as e: # Invalid payload print("#ERR: stripe invalid payload : ", e) return HttpResponse(status=400) except stripe.error.SignatureVerificationError as e: # Invalid signature print("#ERR: stripe invalid Signature : ", e) return HttpResponse(status=400) if event["type"] == "checkout.session.completed": session = event["data"]["object"] # send the email to the user get the email from session and product id print(">> session :: ", session) I'm wondering what if i remove the check for except stripe.error.SignatureVerificationError as e: # Invalid signature print("#ERR: stripe invalid Signature : ", e) return HttpResponse(status=400) and just allow it.(i have no idea would that cause security risks??) -
How to override the generate_filename function of a file name field in the parent class?
I have an abstract class BaseFile and a descendant SeamlessFile. In SeamlessFile, I override the generate_filename method of the BaseFile. Everything works flawlessly. Now if I want a descendant of SeamlessFile, and I want to override only the generate_filename method, this doesn't work, because my wild guess is that generate_filename associated with the actual_file is the one of SeamlessFile. It's ok I understand the problem, but I dont know how to solve it: how to override the generate_filename function of the parent (it's not only override, it's "make the actual_file model use the new function")? class BaseFile(UidMixin, BaseModel): __metaclass__ = ABCMeta upload_directory = "" def generate_filename(self, filename): return "uploads/" class SeamlessFile(BaseFile): def generate_filename(self, filename): return os.path.join("seam/", basename(filename)) actual_file = models.FileField( default=None, null=True, blank=True, upload_to=generate_filename, ) class FrontEndAuditFile(SeamlessFile): def generate_filename(self, filename): print("FrontEndAuditFile -> generate_filename") return os.path.join("fro/", basename(filename)) -
Python dict comprehension on a Django Queryset
In my project i have a Django ORM query for manage some data: var_results = VarsResults.objects.filter( id_res__read_date__range=(start_d, end_d), id_res__proj_code=pr_code, var_id__is_quarterly=False ).select_related( "id_res", "var_id" ).values( "id_res__read_date", "id_res__unit_id", "id_res__device_id", "id_res__proj_code", "var_val" ) well, my query return an Queryset object containing data i need. My problem is that the var_val is a string representation of a dict and i, instead of that value (for example '[54321, 98]') i would convert it using my conversion function def decode_value(original value): ... return <converted value> i would call directly my decode_value function in my queryset creation like this: var_results = VarsResults.objects.filter( id_res__read_date__range=(start_d, end_d), id_res__proj_code=pr_code, var_id__is_quarterly=False ).select_related( "id_res", "var_id" ).values( "id_res__read_date", "id_res__unit_id", "id_res__device_id", "id_res__proj_code", decode_value(var_val) ) but i get an error: var_val is not defined so i thinked about create using a python dict comprehension a dedicated dict stating from my queryset with all queryset field and var_val field converted but i don't know how achieve this. Can somaone help me about dinamicaly value editing in django ORM queryset object creation or in a dict comprehension from a Queryset object? So many thanks in advance -
Set different size for each columns in Reportlab
I am using Reportlab in python. Now I am trying to customize each column width. Because some of the columns need small width rather than other columns. Is there any way to make each column customizable? Currently from the picture, I would like to increase the width of the Partname column width and set small width for tax, Style p, etc. views.py columns = [ {'title': 'Part No', 'field': 'partno'}, {'title': 'Part Name', 'field': 'partname'}, {'title': 'Style P', 'field': 'style'}, {'title': 'Standard P', 'field': 'standardpack'}, {'title': 'Unit Per Car', 'field': 'unit'}, {'title': 'Quantity PCS', 'field': 'quantity'}, {'title': 'Tax', 'field': 'tax'}, {'title': 'Unit Price', 'field': 'price'}, {'title': 'Amount', 'field': 'amount'}, ] table_data = [[col['title'] for col in columns]] table_row = [str(tr.part.partno),tr.part.partname, tr.part.stylepack, tr.part.standardpack,tr.part.unit, tr.quantity, tr.part.tax, tr.part.price, tr.amount] table_data.append(table_row) table = Table(table_data, repeatRows=1, colWidths=[150,150]) table.setStyle(TableStyle([ ('BOX', (0, 0), (-1, -1), 0.20, colors.dimgrey), ('FONT', (0, 0), (-1, 0), 'Helvetica-Bold'), ('INNERGRID', (0, 0), (-1, -1), 0.1, colors.black), ('ALIGN', (0, 0), (-1, -1), 'CENTER'), ('FONTSIZE', (0, 0), (-1, -1), 10), ])) elements.append(table) -
how to set value to Foreign key filed before Perform create in django rest framework
I have two serializers like this : class MeetingLocationSerializer(serializers.ModelSerializer): class Meta: model = MeetingLocation fields = '__all__' class MeetingtSerializer(serializers.ModelSerializer): location = MeetingLocationSerializer() photos = MeetingPhotoSerializer(many = True) class Meta: model = Meeting fields = ['id','title','description','date_time','time_zone','host','is_private','is_virtual','url','photos','location'] and this is my modelviewsets : class MeetingListViewSet(viewsets.ModelViewSet): queryset = Meeting.objects.all() serializer_class = MeetingtSerializer class MeetingPhotoViewSet(viewsets.ModelViewSet): queryset = MeetingPhoto.objects.all() serializer_class = MeetingPhotoSerializer def retrieve(self, request, *args, **kwargs): param = kwargs photos = MeetingPhoto.objects.filter(meeting=param['pk']) serializer = MeetingPhotoSerializer(photos, many =True) return Response(serializer.data) when i want to post data to MeetingListViewSet and save it , the meeting filed in nested location serializer needs value which is the meeting that i am trying to create and it is not created yet! what should i do? -
How to find objects with the most similar fields?
This is the model I have defined: class Book(models.Model): authors = models.ManyToManyField(to='Author') category = models.ForeignKey(to='Category') tags = models.ManyToManyField(to='tags') # some other fields How can I find ten books that are most similar in these three fields (authors, category, tags) to a specific object? -
Django Signals to trigger VersatileImageFieldWarmer on migrations
I have some post_save signals to "create new images immediately after model instances are saved" just as stated on django-versatileimagefield docs. Example: @receiver(models.signals.post_save, sender=VendorImage) def warm_vendor_images(sender, instance, **kwargs): warmer = VersatileImageFieldWarmer( instance_or_queryset=instance, rendition_key_set=settings.VERSATILEIMAGEFIELD_RENDITION_KEY_SETS['default'], image_attr='image', verbose=True ) warmer.warm() This works fine when I upload images and even when creating my fixtures. However, I have two models that are populated in the migrations using RunPython. Example: eventCategories = { "Poolparty": 'Poolparty.png', ... } ... def AddEventCategories(apps, schema_editor): model = apps.get_model('sp_event', 'EventCategory') for key in eventCategories: imagePath = upload_to + eventCategories[key] model.objects.create(name=key, image=imagePath) ... migrations.RunPython(AddEventCategories) I was wondering if the create() method calls save() to trigger the signal, but to be sure 100% sure, I called save() after creating the instances: the signal wasn't triggered as well. Using the VersatileImageFieldWarmer in the migration also results in an error regarding the image path... How can I ensure my sized images are created upon the instances creation during the migration process? -
How to view a model from new app in django admin?
Working with telegram bot with admin on django. There are was 7 apps in project. I create new app,register models in admin.py in app, write app in settings.py, make migrations and migrat, restart supervisor,under that all working, but nothing. Admin path was created with django-admin-tools. I was return all to standart django admin, but models in admin not view. Dont know what can make more. setting.py(without selery): INSTALLED_APPS = [ 'admin_tools', 'admin_tools.theming', 'admin_tools.menu', 'admin_tools.dashboard', 'mptt', "django_cron", 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.postgres', 'django.contrib.humanize', 'cache_model', 'preferences', 'public_model', 'sort_model', 'users', 'server_resources', 'application.telegram', 'application.request', 'application.trucks', 'application.sales', 'application.parsings', 'application.docs', 'application.rating', 'application.check', 'application.subscription', 'application.emirates' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'application.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates'), ], 'APP_DIRS': False, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.i18n', 'django.template.context_processors.media', 'django.template.context_processors.request', 'django.template.context_processors.static', 'django.contrib.messages.context_processors.messages', 'django.contrib.auth.context_processors.auth', ], 'loaders': [ 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', 'admin_tools.template_loaders.Loader', ], 'debug': DEBUG, }, }, ] WSGI_APPLICATION = 'application.wsgi.application' # Database # https://docs.djangoproject.com/en/1.11/ref/settings/#databases # Database DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'telegram_avtorazborov_bot', 'USER': 'postgres', 'PASSWORD': 'postgres', 'HOST': 'localhost', 'PORT': '', } } # Password validation # https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ ] # Internationalization # https://docs.djangoproject.com/en/1.11/topics/i18n/ LANGUAGE_CODE = 'ru-ru' TIME_ZONE = 'Europe/Moscow' USE_I18N = True … -
Why does from . import views work and import views does not?
This question came to my mind while exploring Django. Suppose this structure: . ├── db.sqlite3 ├── manage.py ├── mysite │ ├── asgi.py │ ├── __init__.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py └── myapp ├── admin.py ├── apps.py ├── __init__.py ├── migrations │ └── __init__.py ├── models.py ├── tests.py ├── urls.py └── views.py In polls/urls.py, this statement import views fine: from . import views while just import views raises ModuleNotFoundError. What I understand is that import foo searches for foo in a list of directories defined by sys.path which includes the current package, and also from the documentation: Relative imports use leading dots. A single leading dot indicates a relative import, starting with the current package. So, both import foo and from . foo should work quite the same. If that is true, why it isn't the case for the django imports? If it's not true, what do I misunderstand? -
how to filter between two existing date django
i'm trying to filter and check if two dates are already exists , for example we have this existing two dates 28-6-2021 11:30 PM and 30-6-2021 11:30 PM , i have to prevent the users to select any dates which contains between that two existing dates for example if the user try to select 29-6-2021 12:00 PM to 1-7-2021 12:00 PM it should raise an error the dates already taken ! this is my models.py class Booking(models.Model): room_no = models.ForeignKey(Room,on_delete=models.CASCADE,blank=True,related_name='rooms') check_in = models.DateTimeField(default=datetime.now) check_out = models.DateTimeField() #my form class BookingForm(forms.ModelForm): check_in = forms.DateTimeField(required=True,input_formats=['%Y-%m-%dT%H:%M','%Y-%m-%dT%H:M%Z'],widget=forms.DateTimeInput(attrs={'type':'datetime-local'})) check_out = forms.DateTimeField(required=True,input_formats=['%Y-%m-%dT%H:%M','%Y-%m-%dT%H:M%Z'],widget=forms.DateTimeInput(attrs={'type':'datetime-local'})) class Meta: model = Booking fields = ['check_in','check_out'] and this is my views.py , i've tried this to achieve it @login_required def add_booking(request,room_no): room_number = get_object_or_404(Room,room_no=room_no) if request.method == 'POST': form = BookingForm(request.POST) if form.is_valid(): obj = form.save(commit=False) if room_number.rooms.filter(check_in__gte=check_in,check_out__gte=check_out).exists(): #if room_number.rooms.filter(Q(check_in__gte=check_in, )|Q(check_out__lte=check_out)).exists(): #but still doesnt work return HttpResponse('taken! sorry , try another room please') obj.room_no = room_number obj.save() messages.success(request,f'room number {room_number} added') form = BookingForm() return render(request,'booking/add_booking.html',{'form':form,'room_number':room_number}) but doesn't work , the project is for a hotel , and booking app , i have to prevent users from selecting wrong dates ! please is it possible ? thank you so much .. -
How can we create an endpoint in django for google api client
I am trying to implement login with google in Native kotlin.And using django as a backend. For google api clint I have added python code in my django project. verify_oauth2_token.py from google.oauth2 import id_token from google.auth.transport import request from delopus.settings import CLIENT_ID # (Receive token by HTTPS POST) # ... try: # Specify the CLIENT_ID of the app that accesses the backend: idinfo = id_token.verify_oauth2_token(token, requests.Request(), CLIENT_ID) # Or, if multiple clients access the backend server: # idinfo = id_token.verify_oauth2_token(token, requests.Request()) # if idinfo['aud'] not in [CLIENT_ID_1, CLIENT_ID_2, CLIENT_ID_3]: # raise ValueError('Could not verify audience.') # If auth request is from a G Suite domain: # if idinfo['hd'] != GSUITE_DOMAIN_NAME: # raise ValueError('Wrong hosted domain.') # ID token is valid. Get the user's Google Account ID from the decoded token. userid = idinfo['sub'] except ValueError: # Invalid token pass I am trying to create an endpoint like below urls.py path('user/google/oauth', exampleView.as_view(), name='google_oauth'), In this exampleView I don't have class view. I need class view so that I can create an endpoint. But I am not sure how to create class view in django for endpoint url so that I can validate an ID token using the tokeninfo endpoint. like given … -
How to remove currently, change, clear from Form and still retain instance of UpdateView
I have a task at my internship program where I need to remove change and clear from my form filefield. What I don't get is they don't show up in the createview. As far as I understand both create and update use the same form, the template is the same, the only difference is update is passing an object. I tried from django.forms.widgets import FileInput class SomeForm(forms.Form): foofile = forms.FileField(widget=FileInput) in the form, but then I lost the initial value of the object in update totally. There were no widgets, but there was no file either, which is no good. So what needs to be done here? -
Django TemplateDoesNotExist at /meetups/
error when Django server is run directory installed apps for Django -
How can dropdown list beside search box this on django admin panel?
I want to search things by Dropdown list AND searched text in django model. How can i achieve this for perticular Model in DjangoAdmin section? -
Django Query How to compare field with _set filter condition?
I have following model class Reply(BaseModel): reply_to = models.OneToOneField( Review, on_delete=models.CASCADE, error_messages={'unique': 'Reply to this review already exists.'}) replied_by = models.ForeignKey(HotelUser, on_delete=models.CASCADE) Basically Review model is linked with foreign key with reservation class Review(BaseModel): reservation = models.ForeignKey(Reservation, on_delete=models.CASCADE) and My Reservation Model has Room as Foreign Key as class Reservation(BaseModel): room = models.ForeignKey(Room, on_delete=models.CASCADE) and Room is linked with Hotel in Foreign key class Room(BaseModel): hotel = models.ForeignKey(Hotel, on_delete=models.CASCADE) and I have certain staff model which have hotel as Foreign key in this way class Staff(BaseModel): hotel = models.ForeignKey(Hotel, on_delete=models.CASCADE) user = models.OneToOneField(HotelUser, on_delete=models.CASCADE) My problem is I want the replied by user which is basically ->hotel user lets say XYZ is Staff of `XYZ' hotel. I tried this in clean method: def clean(self): if not self.replied_by.reservation.room.hotel.staff_set.filter(user=replied_by) == self.replied_by: raiseError but there is no any change on restrication any help will be helpful. -
Local development Django static files coming from library directory rather than my project
I have a Django (3.1) app that I've set up to serve static files, that is, DEBUG = True . . . INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'myapp', . . . ] . . . STATIC_URL = '/static/' STATIC_ROOT = 'static/' But instead of serving files from the static directory of myapp, it's serving static files from /Library/Python/3.7/site-packages/django/contrib/admin/static/. I have tested this by adding files to both directories, ~/Projects/myapp/static/file-from-project.js /Library/Python/3.7/site-packages/django/contrib/admin/static/file-from-library.js and then python3 manage.py runserver with a template including the lines <script src="{% static 'file-from-project.js' %}"></script> <script src="{% static 'file-from-library.js' %}"></script> and file-from-library.js loads fine but I get a 404 for file-from-project.js. What am I doing wrong here? -
How to avoid redundant database queries while using serailizer validation and APIViews
There is situation where, in Django serializer, validation of a field needs to query the database for getting an object or a queryset. After successful validation, the APIView again requires to access the same object or query set. In such case how can we avoid duplicate queries? Should we just avoid the validation in the serializer and instead do it in the APIView? Or can we pass the fetched object or queryset to the validated_data attribute of the serializer, so that we can get it in the APIView? Or else, is there a better way? -
Is there any way to customize django-treebeard admin interface for separate dashboard?
Django-treebeard has an awesome admin interface with drag and drop feature. I have implemented it in my project but the requirement is that user won't be given access to django admin and a separate dashboard is created for crud like operations. Is there any way i can use that admin interface in my custom dashboard without losing all the functionality? -
How to make django recognise lines in a TextField
everyone. I have a blog model with the attribute description = models.TextField(). I made a blog the using the django admin interface. On my website, I print all the blogs. In admin, I left newlines (just by pressing enter) in between the paragraphs, but they are displayed as a single paragraph on the website. I know this question is answered here newline in models.TextField() not rendered in template and here New Line on Django admin Text Field, but these solutions use the template tags linebreak and safe and requires you to use \n in your TextField. For any non-programmer using my website, they wouldn't know to use \n. Basically, what I am trying to say is, is there any solution which doesn't require \n in theTextField. I use Django 3.2 and SQLite3. Thanks in advance. -
Register user in django rest framework with connect to database phpmyadmin
I was following this step: https://stackoverflow.com/a/29391122/13240914 to create user registration and login with return jwt. Here is part of the code class UserSerializer(serializers.ModelSerializer): password = serializers.CharField(write_only=True) def create(self, validated_data): user = UserModel.objects.create_user( username=validated_data['username'], password=validated_data['password'], ) return user class Meta: model = UserModel # Tuple of serialized model fields (see link [2]) fields = ( "id", "username", "password", ) So, instead of using validated_data, is there a way to validate username using data inside database phpmyadmin (so when user have been save their username in database, it will return error.. other than that, the username will be save in database) ? I have created database in phpmyadmin, but I didn't know yet how to replace validated_data with validation to check in database -
How to generate JSON from a pandas data frame for dynamic d3.js tree
I'm new to Pandas and have a complex requirement. I have a data frame, which contains multiple columns like the one below Parent Child Color IT;Programming;Trending;Demand Python #6200ea IT;Programming;Trending;Demand Docker #7c4dff IT;Programming;Testing Selenium #b388ff IT;Programming;Old C/C++/C# #ff1744 IT-Tools;Testing HP UFT #aa00ff IT-Tools;IDE PyCharm #9c27b0 I've used str.split(';') to generate multiple Parent columns in the data frame df = df.join(df.Parent.str.split(";", expand=True).add_prefix('branch')) df.drop(columns=['Parent'], inplace=True) print(df) Output: branch0 branch1 branch2 branch3 Child Color IT Programming Trending Demand Python #6200ea IT Programming Trending Demand Docker #7c4dff IT Programming Testing None Selenium #b388ff IT Programming Old None C/C++/C# #ff1744 IT-Tools Testing None None HP UFT #aa00ff IT-Tools IDE None None PyCharm #9c27b0 I need to generate a classification tree for which I need to generate a JSON (along with color value) which is mentioned on the below website https://bl.ocks.org/swayvil/b86f8d4941bdfcbfff8f69619cd2f460#data-example.json Can somebody please help me Thank you! -
date filtering in django with __gte does not add apostrophe
when filtering using __gte on models.DateTimeField the printed query doesn't wrap the searched date with an apostrophe ' this may lead to undesired results in postgres database: WHERE ("appname_tablename"."creation_date" >= 2021-06-27 11:08:29.311284+00:00 AND "appname_tablename"."node_id" = 111) switching to a raw query set which requires further processing since the result needs to go though aggregation and so on, any ideas?