Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django signals error with Foreign Keys - post_delete on related objects gets called before pre_delete on the ForeignKey
I have 2 model classes: class Company: name = models.... pending_delete = BooleanField class User: company = ForeignKey(Company, CASCADE) On the pre_delete of Company, I try to set pending_delete to True, so that I can access it when the post_delete signal of User is called because of CASCADE. However, for some reason the pre_delete signal (of Company) runs after the post_delete signal of User. This might be intended but I'm not sure that I understand why. -
how to solve the Django ORM N+1 Query performance problem when I didn't use Foreign Key
I carried out the development without setting the Foreign Key in the early stages of development because frequent design modifications were difficult. That's how the service is operated, and performance issues such as N+1 Query problems have occurred. If you look for ways to improve performance, I recommend methods such as select_related(), fetch_related(), etc., and I would appreciate it if you could tell me how to improve without using Foreign_Key. It is a service that is already in operation, so it is virtually impossible to apply the Foreign Key one by one. -
Add an ID field in django ORM
I have an Employee model in my django app like the following: class Employee(models.Model): role_choices = (('CRUD', 'CRUD'), ('View', 'View')) user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) company = models.ForeignKey(Company, on_delete=models.CASCADE, related_name="company") name = models.CharField(max_length=500, default=0) email = models.EmailField(max_length=500, default=0) phone = models.CharField(max_length=500, default=0) city = models.CharField(max_length=500, default=0) But now I want to remove this user field but since it's primaryKey it is asking me to do this: You are trying to add a non-nullable field 'id' to employee without a default; we can't do that (the database needs something to populate existing rows). Please select a fix: 1) Provide a one-off default now (will be set on all existing rows with a null value for this column) 2) Quit, and let me add a default in models.py Select an option: providing a value will result in an error since there is no point in giving a single id as default value. How to solve this ? -
What is the correct way to generate a CSV file in Django, Django REST Framework and send it as a streaming response from a POST request?
Generate CSV file using POST request I try to achieve csv download using POST request by below code but not able to get file response it is returning normal response. What will be the valid approach to achieve streaming file response using POST request? import csv from django.http import StreamingHttpResponse from rest_framework.decorators import api_view def generate_csv_data(): # Generate your CSV data here csv_data = [ ['Name', 'Email'], ['John Doe', 'john.doe@example.com'], ['Jane Smith', 'jane.smith@example.com'] ] # Yield each row of CSV data for row in csv_data: yield ','.join(row) + '\n' @api_view(['POST']) def download_csv(request): response = StreamingHttpResponse(generate_csv_data(), content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="data.csv"' return response -
django error in auth user model ValueError: Related model 'pcpartpicker.user' cannot be resolved
I am using django authentication and it keeps giving me this error when I run the migrate cmd ValueError: Related model 'pcpartpicker.user' cannot be resolved This is my model : from django.contrib.auth.models import AbstractUser class User(AbstractUser): pass Functions: from django.shortcuts import redirect , render from .error import error from django.contrib.auth import authenticate, login, logout from django.db import IntegrityError from ..models import User def login_view(request): if request.method == "POST": username = request.POST["username"] password = request.POST["password"] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return redirect("/") else: return error("102", "Invalid username or password", request) else: return render(request, "login.html") def logout_view(request): logout(request) return redirect("/") def register(request): if request.method == "POST": email = request.POST["email"] password = request.POST["password"] confirmation = request.POST["Cpassword"] if password != confirmation: return error("203", "passwords do not match", request) try: user = User.objects.create_user(email, email, password) user.save() except IntegrityError: return error('102', "email in user", request) login(request, user) return redirect('/') else: return render(request, "register.html") login.html {% extends 'layout.html' %} {% block body %} <section class="bg-gray-50 dark:bg-gray-900"> <div class="flex flex-col items-center justify-center px-6 py-8 mx-auto md:h-screen lg:py-0"> <div class="w-full bg-white rounded-lg shadow dark:border md:mt-0 sm:max-w-md xl:p-0 dark:bg-gray-800 dark:border-gray-700"> <div class="p-6 space-y-4 md:space-y-6 sm:p-8"> <h1 class="text-xl font-bold leading-tight tracking-tight text-gray-900 md:text-2xl dark:text-white"> … -
Paginator in View class everytime call request
I have view with paginate_by field by 6 per page and i pull my request from 3rd party api into view queryset So i have question, everytime i go on page 2 or others, queryset is calling request from api again, so i have to wait to page to load that request. I need to load request and paginate trough that request without calling it on another pages of paginator So how am i suppose to do it? views.py class CustomerContractsListView(LoginRequiredMixin, ListView): template_name = 'contracts/customer/contracts.html' context_object_name = 'list_of_contracts' paginate_by = 6 def get_queryset(self): current_object = self.request.GET.get('ObjectGUID') current_counter_party = self.request.GET.get('CounterpartyGUID') url = config('API_ENDPOINT') + 'GetListContracts' if current_object is not None: object_name = ObjectList.objects.get(GUID=current_object) url = config('API_ENDPOINT') + 'GetListContracts' + '?ObjectGUID=' + str(current_object) if current_counter_party is not None and current_object is not None: url = url + '&CounterpartyGUID=' + str(current_counter_party) url = config('API_ENDPOINT') + 'GetListContracts' + '?ObjectGUID=' + str(current_object) + \ '&CounterpartyGUID=' + str(current_counter_party) response = requests.get(url).json() queryset = [] dict_of_counter_party = {} all_counter_party = CounterParty.objects.all() for i in all_counter_party: dict_of_counter_party[i.GUID] = i.name for item in response: my_js = json.dumps(item) parsed_json = ListContractsSerializer.parse_raw(my_js) for counter in parsed_json.ListOfCounterparty: counter.CounterpartyGUID = dict_of_counter_party[UUID(counter.CounterpartyGUID)] queryset.append(counter) for contracts in counter.ListOfContract: contracts.VAT = contracts.VAT * 100 queryset.append(contracts) return … -
Cant update one to one field in django
views.py file Groups.objects.filter(user_id=request.user.id, group_name=product_name).update(category_id=category) models.py file class Groups(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, related_name='Groups_user', unique=False) group_name = models.CharField(max_length=100) links = models.TextField(default='', null=True, blank=True) description = models.TextField(default='', null=True, blank=True) state = models.CharField(default='false', max_length=10) category = models.OneToOneField(ProductCategory, on_delete=models.CASCADE, null=True) Is this correct way to update OneToOne field? I also tried another method but didnt work product = Groups.objects.get(user_id=request.user.id, group_name=product_name) product.category_id = category_id product.save() The error I am getting in pythonanywhere server is OSError: write error. It seems weird. -
Special character and accent marks in Django
I have created a search functionality in django. When I searched for the chateau, it showed the interest with the name Château But when I searched for arpege, it didn't show interest with the name Arpège Here is my code: interest = Interest.objects.filter( Q(name__icontains=searched) | Q(text__icontains=searched) | Q(info1__icontains=searched) | Q(info2__icontains=searched) | Q(info4__icontains=searched) | Q(info5__icontains=searched) | Q(filter_tags__icontains=searched) | Q(meta_description__icontains=searched) | Q(meta_keywords__icontains=searched) ).order_by("-rating") I want to be able to convert all of the special characters in the field "name" in the database first before comparing it with "searched", so I can get the Interest with the name Arpège even if I type arpege. -
Fetching data about tracking Air Cargo with AWB number
I'm a beginner level developer, i want to build a website for AWB (Air Cargo Tracking) tacking. Kindly suggest some ways i can achieve this. I have searched this topic on internet and I'm still confuse about how can i deal with this problem. -
Celery chain of groups and tasks doesn't call next task if group fails
I have created a celery chain that consists of group of tasks and normal tasks, shown below @app.task def task_init(id): # do something print(id) @app.task def task_to_group(id): # do something # raise exception try: print(id) except Exception: raise @app.task def task_status(id): # do something # update the status (end process) if id == 1: id = 2 print(id) @app.task def task_error_handler(id): # do something # handle the failure. update status in db to failed. if id == 1: id = 2 print(id) Created canvas as: id = 1 # this some primary key id from db. chunk = [ task_to_group.si(id).on_error(task_error_handler.s(id)) for id in range(0,5) ] c = chain( task_init.si(id) group(), task_status.si(id) ).on_error(task_error_handler.s(id)) c.apply_async() So, basically the problem I am facing is, if a task in task_to_group fails/raises exception the on_error on that task is called but in the end in the chain the next task to execute be either task_status or on_error``task_error_handler should be called. But none of them are called. The thing I want is, if any task in group fails, the task_error_handler of that group should be called and keep running rest of tasks in group. After group is done the next task either task_status on task_error_handler should … -
How do I fix 'Module social_core.backends.google does not define a GoogleOpenId attribute/class' error in Django login?
I pulled the old Django project but when I log in, I got the following error. Module "social_core.backends.google" does not define a "GoogleOpenId" attribute/class I searched for this error but I can't find any solution. I tried this but not working. Django ImportError: Module "social_core.backends.google" does not define a "GoogleOpenId" attribute/class -
Django/python - boolean checking if id in list of IDs returning false even though it's there?
I am working on the views file for my django project. There is a POST method that checks if an ID is in a list of IDs, but for some reason it's returning false, saying that the posted ID is not in the list. I can see very clearly that it's there. Here is the method: if response.POST.get("followUser"): userToFollowID = response.POST.get("followUser") listOfFollowedUsers = list(userFollowing.objects.filter(username=userInfo.id).values_list('followingList', flat=True)) print(userToFollowID) print(listOfFollowedUsers) print(userToFollowID in listOfFollowedUsers) if userToFollowID not in listOfFollowedUsers: print("we are here?") # t = userFollowing(username = userInfo, followingList = User.objects.get(id=userToFollowID)) # t.save() There's a lot of print statements and jargon, but basically it's supposed to check the POSTed ID and see if it's in the current users list. If the ID is not in the list, it goes into the method and it's supposed to create the database entry. This is the output from the print statements: Output So the POSTed ID in this case is 6, the current user is following [6, 6] (supposed to have unique IDs but will fix afterwards) yet the code print(userToFollowID in listOfFollowedUsers returns false even though it should be True. We get into the if statement and it prints we are here? even though it shouldn't. … -
What is it called when you hash a URL params and map it to the database?
Hi I'm working with Django as my backend and I've been trying to search up this term but I can't seem to find it. For example Spotify has a URL for a song https://open.spotify.com/track/0feI2qZLlaapheeJeznYwZ I'm guessing the hashed ID maps to one of the autogenerated ID's. What would I search up to implement this in my app ? Any references will be greatly appreciated. Thanks in advance :) -
"OperationalError at /checkout table home_checkout has no column named name" in my Django project
Hello to who ever sees this, Hope you all are doing great, I was working on my first Django project and I am facing this error for a while now. I added another form in same format without any hussle but idk why this is happening with this particular form. Hope I could get some help. Thanks in advance. python version - 3.11.3 Django version - 4.2 models.py from django.db import models class Checkout(models.Model): name = models.CharField(max_length=122) email = models.CharField(max_length=122) phone = models.CharField(max_length=122) address = models.TextField() date = models.DateField() def __str__(self): return self.email views.py from django.shortcuts import render,HttpResponse from datetime import datetime from home.models import Checkout def checkout(request): if request.method == "POST": name = request.POST.get('name') email = request.POST.get('email') phone = request.POST.get('phone') address = request.POST.get('address') date = datetime.today() checkout = Checkout(name=name , email = email, phone = phone, address= address, date=date) checkout.save() return render(request, 'checkout.html') HTML code <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Checkout</title> </head> <body> <form action="checkout" method="post"> {% csrf_token %} <input type="text" name="name" id="name" placeholder="Name"> <input type="email" name="email" id="email" placeholder="Email"> <input type="text" name="phone" id="phone" placeholder="Phone number"> <textarea name="address" id="address" placeholder="Please enter your address"></textarea> <input type="submit" name="send" id="send" value="Checkout"> </form> </body> </html> … -
How to implement async view through class-based view(CBV) in Django
An AssertionError occurred while trying to operate asynchronous view as class-based view in django(CBV) The python code i wrote is as follows. urls.py from django.contrib import admin from django.conf.urls import include from django.urls import re_path from rest_framework import routers from blog import views router = routers.DefaultRouter() router.register(r'test', views.TestView, 'hello') urlpatterns = [ re_path(r'^admin/', admin.site.urls), re_path(r'', include(router.urls)), re_path(r'async_view/', include(router.urls)) ] views.py class TestView(viewsets.ViewSet): LOG = logging.getLogger('test') async def list(self, request, *args, **kwargs): self.LOG.info("async method start!!") queryset = Post.objects.none await asyncio.sleep(3) return HttpResponse("Hello async world!") asgi.py import os from django.core.asgi import get_asgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings') application = get_asgi_application() When i execute command below uvicorn mysite.asgi:application --limit-concurrency 12 --reload --host 0.0.0.0 --port 80 then, An AssertionError occurred AssertionError: Expected a `Response`, `HttpResponse` or `HttpStreamingResponse` to be returned from the view, but received a `<class 'coroutine'>` Which part is wrong?? -
React/Django User Register gives me (400 Bad Request)
When I try registering new users through the frontend, it doesn't automatically log me in and it tells me that these new users' emails already exist. From what I can see from Django Admin, the users do get saved/registered and I can login with them. However, it's bothering me that I'm getting these errors and that the new user isn't getting logged in immediately upon creation. This is my first project with Django and redux so any help would be immensely appreciated. Registration Error: {detail: "User with this email already exists"} detail: "User with this email already exists" This is the error I get on the network tab. Console Errors: POST http://localhost:3000/api/users/register/ 400 (Bad Request) Errors that appear on the console Login Errors Errors I get when I login in with an existing user. I don't know if this will effect the function, but my priority is getting the registration issue resolved. RegisterPage.js import React, { useEffect, useState } from "react"; import { Link, useLocation, useNavigate } from "react-router-dom"; import { Form, Button, Row, Col } from "react-bootstrap"; import { useDispatch, useSelector } from "react-redux"; import Loading from "../components/Loading"; import ErrorMessage from "../components/Error"; import FormContainer from "../components/FormContainer"; import { login, … -
How do I Display a Dynamic Message Based on Form Values in a Django Template
I want to display different text based on the checked radio button/form value in a Django template, but I'm not sure how I can get a hold of the value and use it. I tried using the value of the form passed up from the view, but that doesn't update on input change. <div class="form-group"> <label for="radio_choice">Radio Choices</label> <br /> <div class="form-check form-check-inline"> <input class="form-check-input" type="radio" name="radio_choice" id="radio-choice-one" value="RCO" /> <label class="form-check-label" for="radio-choice-one">Radio Choice One</label> </div> <div class="form-check form-check-inline"> <input class="form-check-input" type="radio" name="radio_choice" id="radio-choice-two" value="RCT" /> <label class="form-check-label" for="radio-choice-two">Radio Choice Two</label> </div> <div class="form-check form-check-inline"> <input class="form-check-input" type="radio" name="radio_choice" id="radio-choice-three" value="RCTh" /> <label class="form-check-label" for="radio-choice-three">Radio Choice Three</label> </div> <br /> <small class="text-black-50"> {% if form.radio_choice.value == 'RCO' %} <b>Radio Choice One</b> - Some text about choice one {% elif form.radio_choice.value == 'RCT' %} <b>Radio Choice Two</b> - Some text about choice two {% elif form.radio_choice.value == 'RCTh' %} <b>Radio Choice Three</b> - Some text about choice three {% endif %} </small> </div> -
Troubleshooting Sentiment Analysis in Django Python Project
models.py code file = models.FileField(upload_to='uploads/') result = models.JSONField(null=True) def analyze_sentiment(self): file_path = "D:/python/analyse/uploads" with open(file_path, 'r', encoding='utf-8') as f: input_sentences = f.readlines() stop_words = [] with open('D:/python/analyse/analyse/models/stopwords.txt', 'r') as f: stop_words = [line.strip() for line in f] positive_words = [] with open('D:/python/analyse/analyse/models/positive_words.txt', 'r') as f: for line in f: word, weight = line.strip().split(',') positive_words.append((word, float(weight))) negative_words = [] with open('D:/python/analyse/analyse/models/negative_words.txt', 'r') as f: for line in f: word, weight = line.strip().split(',') negative_words.append((word, float(weight))) emotion_weights = {} with open('D:/python/analyse/analyse/models/emotion_words.txt', 'r') as f: for line in f: word, emotion, weight = line.strip().split(',') if word not in emotion_weights: emotion_weights[word]= {} emotion_weights[word][emotion] = float(weight) # Initialize counters for each sentiment type num_positive, num_negative, num_neutral, num_emotional, num_sarcastic = 0, 0, 0, 0, 0 # Loop through each sentence and analyze its sentiment for sentence in input_sentences: # Tokenize the sentence into words words = sentence.lower().split() # Remove stop words from the sentence words = [word for word in words if word not in stop_words] # Calculate the sentiment score of the sentence sentiment_score = 0 for word, weight in positive_words: if word in words: sentiment_score += weight for word, weight in negative_words: if word in words: sentiment_score -= weight # Determine the overall sentiment of … -
Django Inactivity Middleware not automatically logging user out
After a 10 minute inactivity interval, I want to log my django user out and update a backend value. However, it is only working when I reload my page or send some sort of request to the server after the 10 minute time interval. Here is my current middleware code: from datetime import datetime, timedelta from django.contrib.auth import logout from codera_main.models import UserDetail class InactivityMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): # Check if the user is authenticated if request.user.is_authenticated: # Check if the session has expired if request.session.get_expiry_age() <= 0: # Log out the user and consider them inactive user_detail = UserDetail.objects.get(user=request.user) if user_detail.isCurrentlyActive: user_detail.isCurrentlyActive = False user_detail.save() print(f"User {user_detail.user} is now inactive and logged out.") logout(request) else: # Retrieve the last activity timestamp from the session last_activity = request.session.get('last_activity') # Check if the last activity timestamp exists and is valid if last_activity: last_activity = datetime.fromisoformat(last_activity) time_since_last_activity = datetime.now() - last_activity print(f"User {request.user} last activity: {last_activity}") print(f"Time since last activity: {time_since_last_activity}") # Check if the user is inactive for more than 10 minutes if time_since_last_activity > timedelta(minutes=10): # Log out the user and consider them inactive user_detail = UserDetail.objects.get(user=request.user) if user_detail.isCurrentlyActive: user_detail.isCurrentlyActive = False user_detail.save() print(f"User … -
Validation of the serial number against the mask [closed]
Валидация серийного номера на соответствие маске Есть две таблицы - тип оборудования и оборудование, у типа есть строка с маской серийного номера, у оборудования есть строка с серийным номером. При создании нового оборудования, должна пройти валидация, то есть строку с серийным номером сравнивают с каждой маской типа оборудования и если обнаруживается соответствие - оборудование прявязывается к типу, вопрос такой, как это лучше реализовать на django rest framework? Проверка осуществялется по принципу: N – цифра от 0 до 9; A – прописная буква латинского алфавита; a – строчная буква латинского алфавита; X – прописная буква латинского алфавита либо цифра от 0 до 9; Z – символ из списка: “-“, “_”, “@”. То есть если оборудование имеет серийный номер 0QWER9@123, ему соответствует маска с символами вида NAAAAXZXXX models.py from django.db import models from django.core.validators import MinLengthValidator from django.core.validators import RegexValidator class Type_Of_Equipment(models.Model): name = models.CharField(verbose_name='Тип оборудования', max_length=64, blank=True, default='Без названия') sn_mask = models.CharField(verbose_name='Маска серийного номера', blank=False, max_length=10, validators=[MinLengthValidator(10), RegexValidator(regex=r'^[NAaXZ]+$', message='Использованы недопустимые символы')]) class Equipment(models.Model): code = models.CharField(verbose_name='Код типа оборудования', max_length=64, blank=True) sn_number = models.CharField(verbose_name='Серийный номер', max_length=10, blank=False, unique=True, validators=[MinLengthValidator(10), RegexValidator(regex=r'^[A-Za-z0-9-_@]+$', message='Использованы недопустимые символы')]) type_of_equipment = models.ForeignKey(Type_Of_Equipment, on_delete=models.DO_NOTHING) is_deleted = models.BooleanField(default=False) # Заготовки для мягкого удаления. def soft_delete(self): self.is_deleted = True self.save() def … -
Error regarding git push heroku main command, pywin32 error
When I am trying to push my new project, I have the following errors when I run git push heroku main in my terminal: remote: INFO: pip is looking at multiple versions of pypiwin32 to determine which version is compatible with other requirements. This could take a while. remote: ERROR: Ignored the following versions that require a different python version: 1.9.5 Requires-Python >=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, <3. 7 remote: ERROR: Could not find a version that satisfies the requirement pywin32>=223 (from pypiwin32) (from versions: none) remote: ERROR: No matching distribution found for pywin32>=223 remote: ! Push rejected, failed to compile Python app. remote: remote: ! Push failed This is my requirements.txt file asgiref==3.3.2 astroid==2.4.2 asttokens==2.2.1 backcall==0.2.0 beautifulsoup4==4.9.3 bootstrap4==0.1.0 boto==2.49.0 boto3==1.17.101 botocore==1.20.101 cffi==1.14.5 chromelogger==0.4.3 colorama==0.4.4 comm==0.1.2 debugpy==1.6.6 decorator==5.1.1 distro==1.5.0 dj-database-url==2.0.0 Django==3.2 django-bootstrap3==14.2.0 django-bootstrap4==3.0.1 django-braces==1.14.0 django-crispy-forms==1.11.2 django-debug-toolbar==3.2.1 django-developer-panel==0.1.2 django-misaka==0.2.1 django-storages==1.11.1 django-widget-tweaks==1.4.8 executing==1.2.0 google-compute-engine==2.8.13 gunicorn==20.1.0 houdini.py==0.1.0 importlib-metadata==6.0.0 ipykernel==6.21.2 ipython==8.10.0 isort==5.7.0 jedi==0.18.0 jmespath==0.10.0 jsonpickle==2.0.0 jupyter_client==8.0.3 jupyter_core==5.2.0 lazy-object-proxy==1.4.3 matplotlib-inline==0.1.6 mccabe==0.6.1 misaka==2.1.1 nest-asyncio==1.5.6 numpy==1.24.2 ordereddict==1.1 packaging==23.0 pandas==1.5.3 parso==0.8.1 pickleshare==0.7.5 Pillow==8.2.0 platformdirs==3.0.0 prompt-toolkit==3.0.37 psutil==5.9.4 psycopg2==2.9.6 psycopg2-binary==2.9.6 pure-eval==0.2.2 pycparser==2.20 Pygments==2.9.0 pylint==2.6.0 pypiwin32==223 python-dateutil==2.8.1 pytz==2021.1 pywin32==305 pyzmq==25.0.0 s3transfer==0.4.2 six==1.15.0 soupsieve==2.2.1 sqlparse==0.4.1 stack-data==0.6.2 toml==0.10.2 tornado==6.2 traitlets==5.9.0 typing_extensions==4.5.0 tzdata==2023.3 urllib3==1.26.6 wcwidth==0.2.6 whitenoise==5.2.0 wrapt==1.12.1 zipp==3.14.0 And also I am using python-3.9.16 … -
How to render different UI contexts in a loop within a Django project?
Suppose I have the following code: async def home(request): if request.method == "POST": number = "3" context = {"number": number} return render(request, 'home/home.html', context) I want to have a website that returns different values of the context "3", "2", "1" at the beginning of a game. It would be in a loop similar to this: async def home(request): if request.method == "POST": number = 3 while int(number) < 1: context = {"number": str(number)} render(request, 'home/home.html', context) time.sleep(1) number -= 1 The problem here is that I would think I'd need to return render(request, 'home/home.html', context). But If I return that then I'll break the while loop. How can I then iterate through the values I'd like, and change the UI as required without breaking the loop? Any advice would be appreciated -
In Django display a 100+ list in HTML, which is created in a form, using a dataframe
In django: display a list, which is created in a form, in HTML using a dataframe Can someone please help. I have a django app where I want to display a list of questions in a form which is then displayed in HTMl. But this list of questions can be increased over time (you can update it later). These questions can then be voted on (need drop down list next to it). The initial list of questions is imported from an Excel file then stored in a model then extracted into a dataframe. The problem is that I cannot seem to display all my questions in the forms.py in HTML using the for loop that is in the dataframe. In short, I would like to have a long list (1000 questions) imported into a Model, then extracted into a dataframe, this list must then be displayed in a HTML through a form where people can vote on it then submit. Only the last item in the dataframe presented on the HTML page and not all the questions in the datafram -
What are the alternatives to Quickbooks SDK for pulling data from and to Quickbooks Desktop in Python Django on Ubuntu?
How can I easily integrate Quickbooks (QBO and Desktop) with Python I am developing a web-based syetem Using Django Framework. Running Ubuntu 22.04, Unfortunately the OS am using does not support Quickbooks SDK How can I pull data from and to the Quickbooks Desktop running on a network -
Django Template Inheritance not displaying content, only navigation bar using Jinja
Django Template Inheritance doesn't work I'm using templates inheritance jinja for django, but not work. The navigation bar is displayed, but not the content of user.html or any other page. base.html {% load static %} <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>Panda Particular Professor</title> <meta name="description" content=""> <meta name="viewport" content="width=device-width, initial-scale=1"> <script src="https://kit.fontawesome.com/3297378b0c.js" crossorigin="anonymous"></script> <link rel="stylesheet" href="{% static '/styles/menu.css' %}"/> </head> <body> <nav class="menu"> <a href="#"><div class="navgap User"> <i class="fa-solid fa-user"></i> <label>Mi Usuario</label> </div></a> <a href="#"><div class="navgap Class"> <i class="fa-solid fa-shapes"></i> <label>Clases</label> </div></a> <a href="#"><div class="navgap Dashboard"> <i class="fa-solid fa-graduation-cap"></i> <label>Tablero</label> </div></a> <a href="#"><div class="navgap ClipBoard"> <i class="fa-solid fa-clapperboard"></i> <label>Grabaciones</label> </div></a> <a href="#"><div class="navgap Exit"> <i class="fa-solid fa-door-open"></i> <label>Salir</label> </div></a> </nav> <div id="content"> {% block contenido %} {% endblock %} </div> </body> </html> user.html {% extends "base.html" %} {% block contenido %} <h1>MI USUARIO</h1> <p> {% lorem 25 b random %} </p> {% endblock %} I tried checking the code or using other pages and even restarting the server.