Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
.NET vs Django vs Node [closed]
I'm a beginner at web development. I am considering learning web development and I need to choose a framework. What will you use .NET, Django or Node? I like being the language is typesafe. I'm currently learning C++. Could you please give me advice such as job opportunities, current trends? -
Connection to the another DB not created by Django
I have Django project and want to look the another db (not default db created by Php Symfony) Django can set up two DB in settins.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', "NAME": config("DB_NAME"), "USER": config("DB_USER"), "PASSWORD": config("DB_PASSWORD"), "HOST": config("DB_HOST"), "PORT": config("DB_PORT"), 'OPTIONS': { 'charset': 'utf8mb4', 'init_command': "SET sql_mode='STRICT_TRANS_TABLES'" }, } 'extern': { 'ENGINE': 'django.db.backends.mysql', 'NAME': config("DB_EXTERN_NAME"), 'USER': config("DB_EXTERN_USER"), 'PASSWORD': config("DB_EXTERN_PASSWORD"), 'HOST': config("DB_EXTERN_HOST"), 'PORT': config("DB_EXTERN_PORT"), } } and set models.py for example class Area(models.Model): class Meta: db_table = 'my_area' However it requires to change the extern database when python manage.py makemigrations,python manage.py migrate I just want to reference the extern db not alter. Is there any good practice?? -
Using DRF + frontend framework with Django froms
Background I ran into a really annoying problem here. I've decided to use Svlete as my frontend. Also, I have a lot of endpoints in my REST api that expect form data. In the past I would just forms.py in my app's directory and then add a form like: class ProductsModelForm(forms.ModelForm): class Meta: model = Product fields = ( 'name', 'weight', ) class ProductForm(forms.Form): name = forms.CharField() weight = forms.IntegerField() And would then use <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Submit</button> </form> In the HTML template. All cool. DRF + Frontend Framework Obviously I still have the form in the forms.py but now I have to define the form in the fronend too. And with bigger forms it gets really annoying because I always have to compare that I have every field in my frontend form that I have defined in the django backend form. Is ther any solution to this? -
Trying to make a form with 2 inputs
I have two different forms in my register page as the one to one relationship in one of the model will show a drop down box therefore I am using the second models field where the user will have to input the field. How would I make it so when the forms are valid, the 'SNI' will save to the first form and not the second. Model from asyncio import FastChildWatcher import email from pyexpat import model from xxlimited import Null from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager class userCouncil(BaseUserManager): def create_user(self, userID, password=None): if not email: raise ValueError("Email is required") user = self.model(userID = self.normalize_email(userID)) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, userID, password): user = self.model(userID = self.normalize_email(userID)) user.set_password(password) user.is_staff = True user.is_admin = True user.save(using=self._db) return user class sni(models.Model): SNI = models.CharField(max_length=256, primary_key=True) Used = models.IntegerField(null=True, blank=True) password = None USERNAME_FIELD = 'SNI' def __str__(self): return self.SNI class Account(AbstractBaseUser): userID = models.EmailField(primary_key= True ,max_length=256, unique=True) name = models.CharField(max_length=100) dateOfBirth = models.DateField(max_length=8, null=True) homeAddress = models.CharField(max_length=100, null=True) is_staff = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) sni = models.OneToOneField(sni, on_delete=models.CASCADE, null=True, blank=True) USERNAME_FIELD = 'userID' objects = userCouncil() def __str__(self): return self.userID def has_perm(self, perm, obj=None): return self.is_admin def has_module_perms(self, … -
Django dont create a new instance of a many-to-many field if its field already exists in db, instead increment another field
I have the following classes in my Models.py (removed unrelated fields & classes) class Size(models.Model): prod_size = models.DecimalField(max_digits=3, decimal_places=1) quantity = models.IntegerField(default=1) class Product(models.Model): sizes = models.ManyToManyField(Size, related_name='products') Currently, if I go under a existing product from django admin and add a new size to an existing product with an existing prod_size value (i.e. prod_size = 8.5 with product_id = 4 in the intermediate table) a new Size object (with its new size_id and product_id = 4 in the intermediate table) and prod_size = 8.5 with quantity = 1 in the Size table are created. I would instead like to increment the quantity field of the existing Size object by one in the database, how can I achieve this? -
Websockets problem with django on production
I have a django app and its including websockets, so websockets on running with gunicorn -b 0.0.0.0 or runserver but not working with nginx configuration or problem like that i dont know whats the problem -
Pytest / Django: How to change a decorator that is defined during build time?
I am making a network request and give it a 10 second timeout. The timeout is raised by a decorator that reads the time limit from settings, so it looks like this: @timeout(settings.TIMEOUT). The problem is that I want the test to be super fast, so I change the timeout to 0.1: settings.TIMEOUT = 0.1 The problem is that the decorator is already initialized (I might be using the wrong word) by the time I try to test it. So the decorator is created/defined at build time, then I change the settings, but too late, the decorator doesn't read the updated setting again. Here is a simplified version: ############## settings.py ############### TIMEOUT = 10 ############### request_maker.py ############### from timeout_decorator import timeout from django.conf import settings from time import sleep class MakeRequest @timeout(settings.TIMEOUT) def make_the_request(self): sleep(100) ############### tests.py ############### import pytest from timeout_decorator import TimeoutError from request_maker import MakeRequest def test_make_request(settings): settings.TIMEOUT = 0.1 mr = MakeRequest() with pytest.raises(TimeoutError) as e: mr.make_the_request() # < Even though TIMEOUT is 0.1, it actually times out for 10 seconds How can I change the code so that during production, it is @timeout(10) and during testing it is @timeout(0.1)? -
The best library to add chart in Django Jazzmin admin page
I have 3 models in my Django app and customised user model. I'd like to add few basic bar and pie charts on main admin page. I am using Jazzmin library. Please recommend some libraries or scripts that I can use to create such charts. -
how to Build a referral and earning system in django python
i am currently working on a system, when a user register and do a particular task they will be credited with a certain amount, also the app will have a referral system every user will have a unique referral id when you invite somebody with your code when there do a task you will also earn a certain amount as a referral commission i have already design my data base but i don't know where to start from here, if any one here has build a similar app should please share they code with me, if I didn't deliver this job my work will be at risk thanks -
Embedding http requests into Qt c++ application
I apologize if this is the wrong location to be asking this, let me know and I'll remove it and post it in the right area. I was wondering about standards for performing http requests in a Qt desktop application. For example, I want to create a tool that will register users with a Python based Django application which has a database of users. However, there's a problem here. Do I just hard code the URLs for development and release like this? #ifdef _DEBUG std::string register_url = "http://localhost:3000"; #else std::string register_url = "https://api.mywebsite.com"; #endif I feel like hard coding urls like this is bad practice but I don't know any other way of doing this. Should I use an .ini file? Environment variables? What's the standard for when you have multiple different request URLs? Like I will have the following URLs: /login /register /request_json_web_token /logout /refresh_token Am I supposed to hard code a list of URLs in a header file somewhere? What do you guys do? What's the standard way of doing this? Make monolithic headers full of URLs? -
django raw sql in models with ForeignKey
Let's say this pseudocode represents models to work with class Quiz(): name = models.CharField() class Answer(): quiz = models.ForeignKey(Quiz) answer_text = models.CharField() I would like to trace raw SQL, so let's also import from django.db import connection print(Answer.objects.all().select_related('quiz').query) ok, here we have inner join under the hood >>> a = Answer.objects.all() >>> print(a[0].quiz.query) however the latter example throws AttributeError: 'Quiz' object has no attribute 'query' Could you tell if there are any ways of tracing raw sql more effectively? Which way is the best? I'm practicing more complicated prefetch_related and select_related queries. Thanks -
Settings.BASE_DIR in django returning Windows path instead of Base directory
I ran these commands in the python shell from django.conf import settings print(settings.BASE_DIR) This returned the project's absolute path as expected "C:/Users/User/Desktop/Project" But this was not the case when I tried accessing the same function in a function inside my custom filter, in which it started to return the windows path "C:/" instead. filter.py import os from django import template import moviepy.editor import datetime from django.conf import settings register = template.Library() @register.filter(name='vduration') def vduration(videourl): video = video = moviepy.editor.VideoFileClip(os.path.join(settings.BASE_DIR, videourl)) video_time = int(video.duration) video_time = str(datetime.timedelta(seconds=video_time)) return video_time in my settings.py from pathlib import Path import os BASE_DIR = Path(__file__).resolve().parent.parent Does anyone know what could be going on? -
Python Social Auth grabbing access token for user
I would like to create a custom user with a username, email from the social pipeline using Google OAuth2. If there is a user already associated with that email, username then just attach the access token to that account otherwise create the account but it should get a way to access it through pw after creation? Maybe set a default pw or just delete the account after login? I was looking into pipelines and saw something like this where if backend was something like facebook I could get the values out into a new custom user. { 'username': 'foobar', 'access_token': 'CAAD...', 'first_name': 'Foo', 'last_name': 'Bar', 'verified': True, 'name': 'Foo Bar', 'locale': 'en_US', 'gender': 'male', 'expires': '5183999', 'email': 'foo@bar.com', 'updated_time': '2014-01-14T15:58:35+0000', 'link': 'https://www.facebook.com/foobar', 'timezone': -3, 'id': '100000126636010', } pipeline: def save_profile(backend, user, response, *args, **kwargs): if backend.name == 'facebook': profile = user.get_profile() if profile is None: profile = Profile(user_id=user.id) profile.gender = response.get('gender') profile.save() SOCIAL_AUTH_PIPELINE = ( 'social_core.pipeline.social_auth.social_details', 'social_core.pipeline.social_auth.social_uid', 'social_core.pipeline.social_auth.auth_allowed', 'social_core.pipeline.social_auth.social_user', 'social_core.pipeline.user.get_username', 'social_core.pipeline.user.create_user', 'path.to.save_profile', # <--- set the path to the function 'social_core.pipeline.social_auth.associate_user', 'social_core.pipeline.social_auth.load_extra_data', 'social_core.pipeline.user.user_details', ) My current custom user: class Profile(AbstractUser): bio = models.TextField(max_length=100, blank=True,null=True) phone_number = PhoneNumberField(max_length=25, region='US') birth_date = models.DateField(blank = True, null = True) is_doctor = models.BooleanField(default=False) date_created … -
Django dropdown list of users
I am attempting to create an issue tracker similar to github's. I'm stuck on trying to implement the assigning feature, here's what I have so far class Assign(models.Model): name = models.OneToOneField(User, on_delete=models.SET_NULL, null=True) class Issue(models.Model): MARK_AS = ((True, 'Open'), (False, 'Closed')) title = models.CharField(max_length=100) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) assignee = models.ForeignKey(Assign, on_delete=models.SET_NULL, null=True) mark_as = models.BooleanField(choices=MARK_AS, default=True) def __str__(self): return self.title def get_absolute_url(self): return reverse('issue-detail', kwargs={'pk': self.pk}) admin page I feel like I'm close, however when I try to use class Assign(models.Model): name = models.OneToOneField(User, on_delete=models.SET_NULL, null=True) def __str__(self): return self.name I get the error of __str__ returned non-string (type User) Anyone ideas on how to fix this? Thank you. -
Display data from multiple tables in one Template
I'm trying to create a dashboard for orders placed by a customer. I've got multiple tables, but the two I'm dealing with is "Order" and "Order_Detail". From the "Order" table, I need to display Customer, Status, and Required_date, from the "Order_Detail" table, I need Product. I'm able to access the data but I can figure out how to display all the records at the same time on one page. models.py class Order(models.Model): STATUS = ( ('New', 'New'), ('Ready For Fullfillment', 'Ready For Fullfillment'), ('Fullfilled Ready For Delivery', 'Fullfilled Ready For Delivery'), ('Out For Delivery', 'Out For Delivery'), ('Delivered', 'Delivered'), ) order_date = models.DateTimeField(auto_now_add=True, null=True) required_date = models.DateTimeField(auto_now_add=True, null=True) status = models.CharField(max_length=200, null=True, choices=STATUS) note = models.CharField(max_length=1000, null=True, blank=True) customer = models.ForeignKey(Customer, null=True, on_delete=models.SET_NULL) def __str__(self): return self.customer.name class Order_Detail(models.Model): orderNumber = models.ForeignKey(Order, null=True, on_delete=models.SET_NULL) product = models.ForeignKey(Product, null=True, on_delete=models.SET_NULL) pounds = models.IntegerField(null=True) ounces = models.IntegerField(null=True) container = models.ForeignKey(Container, null=True, on_delete=models.SET_NULL) lot_code = models.CharField(max_length=200, null=True, blank=True) note = models.CharField(max_length=1000, null=True, blank=True) In my views.py, I'm playing with the following code: print('TEST2') o = Order.objects.all() o_notdelivered = Order.objects.exclude(status='Delivered') for e in o_notdelivered: print('Order ID:', e.id) order_detail_data = serializers.serialize("python", Order_Detail.objects.all().filter(orderNumber=e.id)) print('order_detail_data:', order_detail_data) With that code, I'm able to get the ORDER data and … -
What are the correct permissions and virtualhosts for running Django in a sub-directory?
I'm trying to install and run Django in a sub-directory, to keep it separate from a static html site in root, and am having issues with either file/folder permissions or virtualhosts. These two questions haven't helped and are very old: install django on subdirectory and Configure django on sub directory Is this file/folder permissions or virtualhosts issue? Why are the .py files not executing? Running Ubuntu 20.04.3 LTS Apache2 already installed and running Python3 and Django installed libapache2-mod-wsgi installed and enabled Apache restarted several times I ran the usual shell commands to start a Django project: django-admin.py startproject contact and then I ran createsuperuser, collectstatic, etc., successfully. https://example.com/contact/index.html works fine, But this is what I get at example.com/contact/contact: This is my file structure: settings.py: import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = '...' DEBUG = True ALLOWED_HOSTS = [] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] 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 = 'contact.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'contact.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } AUTH_PASSWORD_VALIDATORS … -
graphene-django: Determine Object type when multiple GraphQL object types use the same django model in node query
This is specifically for graphene-django (not just graphene) when performing a node(id: ...) {} query. Assume a fixed schema with 2 (or more) different GraphQL object types using graphene_django.DjangoObjectType linked to the same django model: import graphene_django from .models import Org as OrgModel class Org(graphene_django.DjangoObjectType): class Meta: model = OrgModel fields = ( "id", "name", "billing" ) class AnonymousOrg(graphene_django.DjangoObjectType): class Meta: model = OrgModel fields = ( "id", "name", ) Let's assume a query to Org of ID 7eca71ed-ff04-4473-9fd1-0a587705f885. btoa('Org:7eca71ed-ff04-4473-9fd1-0a587705f885') 'T3JnOjdlY2E3MWVkLWZmMDQtNDQ3My05ZmQxLTBhNTg3NzA1Zjg4NQ==' { node(id: "T3JnOjdlY2E3MWVkLWZmMDQtNDQ3My05ZmQxLTBhNTg3NzA1Zjg4NQ==") { id __typename ... on Org { id } } } Return: { "data": { "node": { "id": "QW5vbnltb3VzT3JnOjdlY2E3MWVkLWZmMDQtNDQ3My05ZmQxLTBhNTg3NzA1Zjg4NQ==", "__typename": "AnonymousOrg" } } } It returns the other object type 'AnonymousOrg:7eca71ed-ff04-4473-9fd1-0a587705f885', despite the relay ID specifying it was an Org object. Is there a way in graphene-django to "hint" or provide detail to assure the return type if what's specified in the ID and its fragment? Clarification on question Other questions were discussing graphene, not specifically graphene-django, which is doing the type determinations in this case. This is different from Django-graphene multiple types for the same model, as that one asked about how to handle field permissions and opened possibility to reconsidering schema structure (e.g. splitting … -
Django Test Update View(edit) error(AssertionError: 'Test Description' != 'Edited Test Description')
I wrote an edit test, the response status code is working very fine which is 302 but I went ahead to assertEquals to the updated content but it was throwing assertion error. MODELS class Banner(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=150 , unique=True) description = RichTextField(blank=True, null=True) category = models.CharField(max_length=200) tag = models.CharField(max_length=200) image = models.ImageField(upload_to='banner-images/') slug = models.SlugField(unique=True, max_length=100) def __str__(self): return self.name def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.name) return super(Banner, self).save(*args, **kwargs) VIEWS @login_required(login_url='login') def editBanner(request, slug): banner = get_object_or_404(Banner.objects.all(), slug=slug) if request.user == banner.user: form = BannerForm(instance = banner) if request.method =="POST": form = BannerForm(request.POST, request.FILES, instance = banner) if form.is_valid(): form.save() return redirect('home') context = {'form':form, 'banner':banner} return render(request, 'edit-banner.html', context) return redirect('home') URLS from django.urls import path from . import views urlpatterns = [ path('banner/<slug:slug>/edit/', views.editBanner, name='edit-banner'), ] TEST def test_edit_banner(self): new_banner = Banner.objects.create( name='The Test Banner', description='Test Description', category='testcategory', user= self.user, slug= 'the-test-banner', tag='testtag', image='testimage.jpg', ) response = self.client.post(reverse('edit-banner', args=['the-test-banner']), { 'name': 'The Test Banner', 'description': 'Edited Test Description', 'category': 'testcategory', 'user': self.user, 'tag': 'testtag', 'image': 'testimage.jpg', }) self.assertEquals(response.status_code, 302) new_banner.refresh_from_db() self.assertEquals(new_banner.description, 'Edited Test Description') But I keep getting this error after many tweaking I want to get the … -
Django Form has no attribute get
I have an form class EntryForm(forms.ModelForm): status = forms.ChoiceField( choices=Maca.Status.choices, widget=forms.RadioSelect(attrs={"class": "radio-ul"}), ) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) class Meta: model = Entry fields = ["status", "commission"] I try to update the object with class based view def post(self, request, *args, **kwargs): entries = UsersProductConfig.objects.get(pk=request.POST["object_id"]) maca = EntryForm(request.POST or None, instance=entries) if maca.is_valid(): maca.save() return maca But I got the following error 'EntryForm' object has no attribute 'get' -
Postgres in Docker/ Django app does not work - OperationalError: could not connect to server: Connection refused
I have a Django app that runs locally with no problems. Now, I want to get a docker image of my app but when I try to build it, it gives me the following error: django.db.utils.OperationalError: could not connect to server: Connection refused Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5432? could not connect to server: Cannot assign requested address Is the server running on host "localhost" (::1) and accepting TCP/IP connections on port 5432? I am new on Django and Docker development and i was looking for similar questions but none answer solved my problem. I'll show you my Dockerfile, I have copied the Postgres commands from another project that does work: FROM python:3.8 RUN apt-get update RUN mkdir /project WORKDIR /project RUN apt-get install -y vim COPY requirements.txt /project/ RUN pip install -r requirements.txt COPY . /project/ # Install postgresql RUN apt install -y postgresql postgresql-contrib RUN service postgresql start # Run the rest of the commands as the ``postgres`` user created by the ``postgres-9.3`` package when it was ``apt-get installed`` USER postgres # Create a PostgreSQL role RUN /etc/init.d/postgresql start &&\ psql --command "CREATE USER admin WITH SUPERUSER PASSWORD 'administrador';" … -
Django related_name with _set function
I'm using related_name tag in my models and I'm trying to filter my form with _set function. However I'm having this error; AttributeError: 'Client' object has no attribute 'contact_owner_set' I think the problem is in right here; self.fields['contact_owner'].queryset = self.instance.client_owner.contact_owner_set.order_by('name') I've tried to remove related_name field and change this bit to; self.fields['contact_owner'].queryset = self.instance.client_owner.contact_owner_set.order_by('name') However I need related_name for my other functions. Is there any way to figure this out? models.py from django.db import models from django.contrib.auth.models import User from django.urls import reverse class Client(models.Model): name = models.CharField(max_length=100) def get_absolute_url(self): return reverse("client-detailview", kwargs={"slug": self.slug}) def __str__(self): return str(self.name) class Contact(models.Model): client_owner = models.ForeignKey(Client,on_delete=models.CASCADE, related_name='contact_client') # client.contact_client name = models.CharField(max_length=100) def get_absolute_url(self): return reverse("contact-detailview", kwargs={"slug": self.slug}) def __str__(self): return str(self.client_owner) + " - " + str(self.name) class Action(models.Model): client_owner = models.ForeignKey(Client,on_delete=models.CASCADE, related_name='action_client') # client.action_client contact_owner = models.ManyToManyField(Contact, related_name='action_contact', blank=True, null=True) # contact.action_contact topic = models.CharField(max_length=100, blank=True, null=True) def __str__(self): return str(self.topic) + " - " + str(self.user_owner) + " - " + str(self.client_owner) + " - " + str(list(self.contact_owner.all().values_list('name', flat=True))) views.py from django.shortcuts import render from django.views.generic import ListView, CreateView, UpdateView from django.urls import reverse_lazy from .models import Action, Contact from .forms import ActionForm class ActionListView(ListView): model = Action context_object_name = … -
cycle through output and add to database
An API call returns some data that I want to upload into the database, it returns about 5000 records. I only want to run this manually when needed. [ { "id": "01", "symbol": "xyz", "name": "xyz" }, { "id": "02", "symbol": "abc", "name": "abc" }, { "id": "04", "symbol": "fhf", "name": "fhf" }, { "id": "05", "symbol": "gxfg", "name": "gxfg" }, ] Is there a way I can cycle through each one and upload it to a model? The model will have matching field names os ID Symbol and Name -
Django AllAuth redirecting to signin for for First and Last name despite not required
I'm using Django AllAuth and trying to let people instantly log in with Discord. When they do that, it takes them to a signup form that forces them to enter their First and Last Name. These are not required fields in my user model so I have no idea why this would be forced. Here are my settings: # Authentication - Using AllAuth ACCOUNT_AUTHENTICATION_METHOD = "email" ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_EMAIL_VERIFICATION = "optional" ACCOUNT_CONFIRM_EMAIL_ON_GET = False ACCOUNT_LOGOUT_ON_GET = True ACCOUNT_EMAIL_CONFIRMATION_EXPIRE_DAYS = 180 ACCOUNT_USERNAME_REQUIRED = False ACCOUNT_ACTIVATION_DAYS = 360 LOGIN_URL = '/login/' LOGOUT_URL = '/account/logout/' LOGIN_REDIRECT_URL = '/' LOGOUT_REDIRECT_URL = '/' SOCIALACCOUNT_EMAIL_REQUIRED = False SOCIALACCOUNT_FORMS = {} SOCIALACCOUNT_QUERY_EMAIL = False -
How to print Django Ajax return as Template Data?
I want to print Products data returned by following views on template. When I check the context its printing the correct data but when I try to print data in template it shows nothing. I checked Networks inside browser console, data is called there but I dont know why its not printing to views Template {% for product in products%} {{product.name}} {%endfor%} My Ajax: $(document).ready(function() { var compare = localStorage.getItem("comparisionItems"); var compareObj = JSON.parse(compare); console.log(compareObj) $.ajax({ url: './compare', type: "POST", data: compare, headers: { "X-CSRFToken": $.cookie("csrftoken") }, dataType: "json", contentType : "application/json", processData: "false", success: function (data) { location.reload(); }, }); }); Views.py def compare(request): is_ajax = request.headers.get('X-Requested-With') == 'XMLHttpRequest' if is_ajax and request.method == "POST": data = json.loads(request.body) compare_ids = data['itemIds'] products = Products.objects.filter(id__in=compare_ids) print(products) context={'products':products} return render(request,'./compare.html', context) else: return render(request,'./compare.html') -
Convert tuple and nested dictionary to DataFrame
I have the following code in my function get_context_data(self, **kwargs): def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['uploaded'] = self.request.session['uploaded'] context['selection'] = self.request.session['selection'] dict_comparaison_p1 = dict(enumerate(context['uploaded'].items())) list_comparaison_p2 = context['selection'] dict_comparaison_p2 = {number: dict_comparaison_p1[number] for number in list_comparaison_p2} pprint(dict_comparaison_p2) My dict_comparaison_p2 has the following output: {0: ('Product', {'0': 'Smartwatch', '1': 'Shoes', '2': 'Necklace'}), 1: (' Weight', {'0': 2, '1': 50, '2': 40}), 2: (' Price', {'0': 100, '1': 240, '2': 230})} I want to convert it to a DataFrame like that: Product Weight Price 0 Smartwatch 2 100 1 Shoes 50 240 2 Necklace 40 230 But when I try to convert it with my output, I have the following result: 0 1 2 0 Product Weight Price 1 {'0': 'Smartwatch', '1': 'Shoes', '2': 'Neckla... {'0': 2, '1': 50, '2': 40} {'0': 100, '1': 240, '2': 230} Could you please help me with that? Thanks!