Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Group by users in django ORM
I've a StudentAnswer model which stores the answer id given by the student(User) in a quiz. If the answer is correct then 1 marks else 0. I'm also ranking the users based on their marks in a particular quiz. The model looks like this: class StudentAnswer(models.Model): user = models.ForeignKey(User, related_name='user_question_answer', on_delete=models.SET_NULL,null=True, blank=True) answer = models.ForeignKey(QuizQuestionAnswer, related_name='user_answer', on_delete=models.CASCADE) quiz = models.ForeingKey(Quiz, on_delete=models.CASCADE) marks = models.IntegerField() This is the query I'm using to rank my users: StudentAnswer.objects.filter( quiz__start_date__month=date.today().month).annotate( rank=Window(expression=DenseRank(), order_by=[F('marks').desc(),]) ) A user will have multiple entries in table(number of questions he attempted in a month). I want to group by each user, add their marks and then rank them for that particular month and send the response. How can I do this? Thanks in advance. -
django-two-factor-auth's user.is_verified() returns False on subdomains
I am facing this strange issue, I have posted it here already but didn't get any response yet. I am using django-two-factor-auth in my Django application, Everything works fine in the local environment but getting an issue on the production server. My application is tenant-based and I am using subdomains for each tenant, for example on the production server, My application => xyz.com User with tenant name "a" after login gets redirected to => a.xyz.com User with tenant name "b" after login gets redirected to => b.xyz.com When redirected to a subdomain I am getting this issue that user.is_verified() always returns False even if 2fa is enabled for the user. I am using user.is_valrified() for showing enable/disable 2fa buttons. If I remove the subdomain redirection, it works fine and returns True if 2fa is enabled for a user. My Environments Browser and version: Google Chrome Version 103.0.5060.114 Python version: 3.8.10 Django version: 2.2.0 django-otp version: 0.9.4 django-two-factor-auth version: 1.12.1 Note: I have debugged this enough that I know this is happening due to sub-domains -
Seeing 'SignupForm' object has no attribute 'instance' on Django Form
I am on Django 4.0.x and running over and over into the same issue when validating a form. Always seeing: 'SignupForm' object has no attribute 'instance' Here is my view: def signup(request): if request.method == "POST": signup_form = SignupForm(request.POST) if signup_form.is_valid(): email = signup_form.cleaned_data['email'] else: signup_form = SignupForm() return render(request, 'signup.html', {'signup_form': signup_form}) and the according forms.py: class SignupForm(forms.Form): email = forms.EmailField(label=_("E-Mail Address"), validators=[EmailValidator()]) password = forms.CharField(label=_("Password"), widget=forms.PasswordInput()) password_confirm = forms.CharField(label=_("Confirm Password"), widget=forms.PasswordInput()) def clean_email(self): data = self.cleaned_data['email'] if forms.ValidationError: self.add_error('email', forms.ValidationError) return data def clean_password(self): data = self.cleaned_data['password'] try: validate_password(data, self.instance) except forms.ValidationError as error: self.add_error('password', error) return data cleaned_data also delivers nothing here. -
I am new to Django and working on a project. In my project I need to call a same API from multiple places with different "permission_classes"
I am new to Django and I am working on project for a Blood bank. in my project I have created an API and provided a custom permission class. However I need to call the same API in my project but at different location (in different app). So do I need to create another API for that or I can call the same with a different permission class. So the API I have created in an app named "Form_Hospital > views.py" and this is the code:- class RequisitionFormAV(APIView): ''' to post a "Requisition Form" and get list. ''' permission_classes = [IsAuthenticatedActiveHospitalStaff] # permission_classes = [IsAdminUser] def get(self, request): search = request.query_params.get('search') page = request.query_params.get('page') qty = request.query_params.get('qty') snippet= RequisitionForm.objects.all() if search: snippet = snippet.filter( Q(requisition_no__icontains=search) | Q(requested_name__icontains=search) | Q(organization_name__icontains=search) | Q(contact_no__exact=search) ) output = RequisitionFormSerializer(snippet, many=True).data if page and qty: output = paginations.page(output, qty, page) return Response({'data': output}, status=status.HTTP_200_OK) def post(self, request): data = request.data # getting the organization name of logged in user data['organization_name'] = request.user.organization.value # getting the last DonorRegistrationForm object. try: snippet = RequisitionForm.objects.all().last().requisition_no _str = snippet[5:] _num = int(_str) + 1 _len = len(str(_num)) if _len == 1: _str = "000" + str(_num) if _len == … -
How to **dynamically display** different pages using one html page
I know I have asked this question before but I am really struggling on this issue. I am currently making a shopping website using django and I want to dynamically display the data. The 'shoppingpage' lists the categories and subcategories of clothes. If I click on 9-6 wear, only the images of 9-6wear clothes should come. For example, as shown in the image above when I click on 9-6wear, I get images of 9-6 wear,but the issue is that when I click on other categories(like Fusion wear bridal wear desi swag), I get the same clothes as I got in 9-6 wear. How do I make sure that I get clothes belonging to 'bridal wear' when I click bridal wear and so on using django and html and displaying the data dynamically? below are the functions ,urls ,html pages url path('category/',views.category,name="category") function def category(request): prod = Products.objects.filter(isactive=True) return render(request,'polls/category.html',{'products':prod}) category.html {% for product in products %} <li class="product-item wow fadeInUp product-item rows-space-30 col-bg-4 col-xl-4 col-lg-6 col-md-6 col-sm-6 col-ts-6 style-01 post-24 product type-product status-publish has-post-thumbnail product_cat-chair product_cat-table product_cat-new-arrivals product_tag-light product_tag-hat product_tag-sock first instock featured shipping-taxable purchasable product-type-variable has-default-attributes" data-wow-duration="1s" data-wow-delay="0ms" data-wow="fadeInUp"> <div class="product-inner tooltip-left"> <div class="product-thumb"> <a href="{% url 'polls:productdetails' product.id … -
AttributeError at /accounts/register/ Manager isn't available; 'auth.User' has been swapped for 'stackapp.CustomUser'
from django.db.models import Count "imorting the packges" from django.shortcuts import render, HttpResponse from django.core.paginator import Paginator from django.contrib import messages from .models import * from .forms import AnswerForm, QuestionForm, ProfileForm from django.contrib.auth.forms import UserCreationForm from .forms import ProfileForm from django.conf import settings User = settings.AUTH_USER_MODEL # Home Page def home(request): "creating a function for paginator" if 'q' in request.GET: q = request.GET['q'] quests = Question.objects.filter(title__icontains=q).order_by('-id') else: quests = Question.objects.all().order_by('-id') paginator = Paginator(quests, 10) page_num = request.GET.get('page', 1) quests = paginator.page(page_num) return render(request, 'home.html', {'quests': quests}) # Detail def detail(request, id): "creating a function for question details" quest = Question.objects.get(pk=id) tags = quest.tags.split(',') answers = Answer.objects.filter(question=quest).order_by('-id') # comments = Comment.objects.filter(answer=answer).order_by('-id') answerform = AnswerForm if request.method == 'POST': answerData = AnswerForm(request.POST) if answerData.is_valid(): answer = answerData.save(commit=False) answer.question = quest answer.user = request.user answer.save() messages.success(request, 'Answer has been submitted successfully') return render(request, 'detail.html', { 'quest': quest, 'tags': tags, 'answers': answers, 'answerform': answerform, }) # User Register def register(request): form=UserCreationForm if request.method=='POST': regForm=UserCreationForm(request.POST) if regForm.is_valid(): regForm.save() messages.success(request,'User has been registered!!') return render(request,'registration/register.html',{'form':form}) views.py "importing package" from dataclasses import field from django.forms import ModelForm from .models import Answer, CustomUser, Question class AnswerForm(ModelForm): "creating answerform" class Meta: model = Answer "fetch all field" fields = ('detail',) … -
Graphene-file-upload handling the multipart/form-data
I am trying to upload an image from my react/nextJS front end to my django backend using graphQL and graphene-file-upload. This is the frontend - the important functions here are handleSelectedLogo and submitVendor const CreateVendorForm = () => { // redux state const user = useSelector(selectUser); const token = useSelector(selectToken); const [step, setStep] = useState(1) const inputRef = useRef(null) const [companyName, setCompanyName] = useState('') const [companyAddress, setCompanyAddress] = useState<any>({label: ''}) const [companyLatLng, setCompanyLatLng] = useState<any>({lat: 40.014, lng: -105.270}) const [companyPhone, setCompanyPhone] = useState('') const [companyEmail, setCompanyEmail] = useState('') const [companyWebsite, setCompanyWebsite] = useState('') const [companyLogo, setCompanyLogo] = useState() const [companyDescription, setCompanyDescription] = useState('') const [published, setPublished] = useState(false) const [type, setType] = useState(['Customer Care', 'Information Technology','Market Research', 'Marketing and Communications', 'Renewable Energy', 'Technical Engineering', 'Other']) const [selectedTypes , setSelectedTypes] = useState<string[]>([]) const [showtext, setShowText] = useState(false) const [file , setFile] = useState() useEffect(() => { console.log(token,user) }, []) const toggleType = (type: string) => { if (selectedTypes.includes(type)){ setSelectedTypes(selectedTypes.filter(t => t !== type)) } else { setSelectedTypes([...selectedTypes, type]) } console.log(selectedTypes) } const changeStep = (nextStep: number) => { if(nextStep > 0) { if(step < 4) { setStep(step + 1) } } if (nextStep < 0) { if (step > 1) { … -
SplitDateTimeField default value is not localized
So I have this field in a form: date_time = forms.SplitDateTimeField(required=False, localize=True, label=_("Change the date and time"), ) and initially, the page looks like this: even though I have localize set to True. After I select another date from the datepicker, the date will be localized properly. I'd like the date to be localized from the start. How can I do that? Thanks. -
How to create a user group in django?
I want to create a user group through API, when I created a view to create a group, it shows error like this. Creating a ModelSerializer without either the 'fields' attribute or the 'exclude' attribute has been deprecated since 3.3.0, and is now disallowed. Add an explicit fields = 'all' to the GroupSerializer serializer MySerializer from django.contrib.auth.models import Group class GroupSerializer(ModelSerializer): class Meta: model = Group field = '__all__' MyView class GroupView(APIView): def post(self, request, tenant, format=None): tenant = get_tenant(tenant) serializer = GroupSerializer(data=request.data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data, status=status.HTTP_201_CREATED, safe=False) return JsonResponse(serializer.errors, status=status.HTTP_400_BAD_REQUEST, safe=False) -
How to change template and then continue writing function?
So... I have a function to send email to user and then user has to input the body of that email. My views.py: def signup(request): if request.method == "POST": context = {'has_error': False, 'data': request.POST} email = request.POST.get('email') username = request.POST.get('username') password = request.POST.get('password') code = request.POST.get('code') letters = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"] numbers = ["1", "2", "3", "4", "5", "6", "7", "8", "9",] characters = letters + numbers length = 5 token = "".join(random.sample(characters, length)) body = render_to_string('authentication/email/email_body.html', { 'username': username, 'token': token, }) send_mail( "Email Confirmation", # f"Hello {username}! Your code to confirm your email is : {token}", body, 'tadejtilinger@gmail.com', [email] ) return render(request, 'authentication/email/email_confirmation.html', context={'token': token}) return render(request, 'authentication/signup.html') So here I tried to change template from signup.html to email_confirmation.html. I succeeded so now I want to tell python what it should do with email_confirmation.html but I don't know how to do it. If I try writing code under return render(request, 'authentication/email/email_confirmation.html', context={'token': token}) it won't work. Where should I actually write my code then? Thanks for help I hope I wrote question understanding!:) -
How to write test case for a Django model which has all the fields as foreignkey in DRF?
I have a model which has all the fields as a foreign key to other models. How can we create test case in Django rest framework in that case?? I have a model as follows: class Example(models.Model): package = models.ForeignKey( Destination, related_name="packages", on_delete=models.CASCADE ) user = models.ForeignKey( User, on_delete=models.CASCADE, null=True, related_name="user_packages", ) tour = models.ForeignKey( Tours, on_delete=models.CASCADE, null=True, related_name="tour_packages", ) In a model, when there is just one field in a Django model, it can be done in the following way: class NewsLetter(models.Model): NewsLetterID = models.AutoField(primary_key=True) Email = models.CharField(max_length=255) Connected = models.BooleanField(default=False) UserID = models.ForeignKey(User, on_delete=models.CASCADE) class Meta: db_table = 'NewsLetter' @classmethod def setUpTestData(cls): #Set up non-modified objects used by all test methods user = User.objects.create(<fill params here>) NewsLetter.objects.create(NewsLetterID=1, Email='test@test.com', Connected=False,UserID=user) So even if I have created all the objects for all the foreign-key fields just like this example, the thing is, for the related field models, they themselves have foreign key fields. How can we approach this?? For example in my Example model, the Destination model is itself related to other foreign key fields. So how to create unit test for create api for this Example model?? -
How to filter django queryset based on hours range?
class MyModelSerializer(serailizers.ModelSerializer): hour = serializers.SerializerMethodField() def get_hour(self, obj): created_at = obj.created_at # datetime now = datetime.now() return (now - datetime).total_seconds() // 3600 class Meta: model = MyModel fields = "__all__" In the api there are 3 static filter parameters: filter list upto 3 hr filter list between 3 to 12hr filter list above 12 hr How can I filter below api based on the hour that has been calulated in the above serializer ? For example if I filter by upto3 then the list should return all the objects having hr less or equal to 3. The below way returns if the hours matches the exact value only. @api_view(["GET"]) def get_list(request): qs = MyModel.objects.all() hr = request.GET.get("hr") if hr: hr = int(hr) frm = now() - timedelta(hours=hr+1) to = now() - timedelta(hours=hr) qs = qs.filter(created_at__range=(frm, to)) return MyModelSerializer(qs, many=True).data -
Read tables in Remote mysql database with Django SSH tunnel
I Stuck with it. I have access to remote MySQL database using ssh tunnel with IP, Port, ssh username, ssh password and using database credential with Server Host,Port, DB Name, user and password. I can access to this MySQL remote database in DBeaver and Putty using ssh tunnel and database credential In my Django application, in settings.py ssh_tunnel = SSHTunnelForwarder( (sshIpAdd, sshPort), ssh_username=sshUser, ssh_password=sshPass, ssh_proxy_enabled=True, # ssh_config_file=None, remote_bind_address=('127.0.0.1', 3306), ) ssh_tunnel.start() print(ssh_tunnel.local_bind_port) con=mysql.connector.connect(database=dbName, host='localhost', user=dbUser, password=dbPass, auth_plugin='mysql_native_password', charset='utf8', port=ssh_tunnel.local_bind_port) if con!=None: print("Connected to Mysql Remote Database") else: print("Sql Not Connected") it produce successfull output, and display Connected to Mysql Remote Database (py39) X:>python manage.py runserver 65116 Connected to Mysql Remote Database 65122 Connected to Mysql Remote Database Performing system checks... System check identified no issues (0 silenced). July 20, 2022 - 12:55:06 Django version 3.2.9, using settings 'test.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. When I run Command 'python manage.py inspectdb --database=remote_db' it successfully created model structure from remote database. The problem is when I access remote database in DATABASES with multiple database, DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': defaultDBName, 'USER': 'postgres', 'PASSWORD': defaultDBPass, 'HOST': 'localhost', 'PORT': '5432', }, 'remote_db': { 'ENGINE': 'django.db.backends.mysql', 'HOST': … -
Where is my cache and how to keep it in Redis?
Django==4.0.6 django-cachalot==2.5.1 I use django-cachalot. settings.py CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis://127.0.0.1:6379/1", "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", }, 'TIMEOUT': None, } } I warm the cache up. As you can see, there is something in the cache. But to the best of my ability I can see that Redis is empty. Could you help me understand where is my cache now? It is stored somewhere, but I can't understand where it is. And I seem to have made a blunder here, I have to correct it and keep the cache in Redis. Could you help me? -
How to make Dynamic page for Shopping CRUD
I am making a shopping CRUD and dynamically displaying data. When I press on category '9-6wear' ,I get clothes belonging only to the 9-6wear category ,the issue is that when I press on other categories(as shown in image below) ,I end up with clothes belonging to 9-6wear as well. If I try using the 'id', the issue would be is that I would end up with only 1 product in category below are the codes that I have used function def category(request): prod = Products.objects.filter(isactive=True) return render(request,'polls/category.html',{'products':prod}) def shoppingpage(request): cat = Category.objects.filter(isactive=True) subcat = SUBCategories.objects.filter(isactive=True) # category= CategorySerializer(cat,many=True) # subcategory = SUBCategoriesSerializer(subcat,many=True) hm = {'category':cat,'subcategory':subcat} return render(request,'polls/shoppingpage.html',hm) url path('shoppingpage/',views.shoppingpage,name="shoppingpage"), path('category/',views.category,name="category"), shoppingpage.html {% for result in category %} <div class="col-md-3"> <div class="lynessa-listitem style-01"> <div class="listitem-inner"> <a href="{% url 'polls:category' %}" target="_self"> <h4 class="title">{{result.category_name}}</h4> </a> {% for ans in result.subcategories_set.all %} <ul class="listitem-list"> <li> <a href="/kurta" target="_self">{{ans.sub_categories_name}}</a> </li> </ul> {% endfor %} </div> </div> </div> {% endfor %} help is greatly appreciated, thanks! -
Not able to connect to test database
I was trying to create some dummy data for testing using faker. My tests cases runs and passed successfully as we can see in the ss below, but the database table for Author Model is empty. I assume this might be because of database connection failure or some code error? What should be the right approach for such cases? Any solutions? My settings.py DATABASES={ 'default':{ 'ENGINE':'django.db.backends.postgresql', 'NAME':'postgres', 'USER':'postgres', 'PASSWORD':'welcome4321', 'HOST':'localhost', 'PORT':'5432', } } My factory.py named as factoryboy.py import factory from django.contrib.auth.models import User from faker import Faker from polls.models import Author fake = Faker() class AuthorFactory(factory.django.DjangoModelFactory): class Meta: model = Author name=fake.name() My model.py from django.db import models class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) class Author(models.Model): name=models.CharField(max_length=200) class Account: def __init__(self, username, email, date_joined): self.username = username self.email = email self.date_joined = date_joined def __str__(self): return '%s (%s)' % (self.username, self.email) my Conftest.py import pytest from pytest_factoryboy import register from factoryboy import AuthorFactory register(AuthorFactory) My test_ex5.py from argparse import Action from collections import UserDict from unittest.mock import Base from django.conf import UserSettingsHolder import pytest from sqlalchemy import create_engine from polls.models import Author from sqlalchemy.orm … -
ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. DJANGO_SETTINGS_MODULE or call settings.configure()
django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. I'm new to django, writing a blog for myself. I have created a blog app, written on models.py. Here my code:enter code here from django.db import models # Create your models here. class Post(models.Model): title= models.CharField(max_length=100) body= models.TextField() date= models.DateTimeField(auto_now_add=True) -
Vue not displaying results from Django Rest API data
I am working on a brand new project using Vue and Django Rest Framework. I got the API set up and I am getting the data back as needed. However, I am having an issue with the v-for loop displaying the results. Any reasons or ideas on why I am not getting the results displayed? Here is vue.js code (GetTasks.vue) <template> <div class="tasks"> <BaseNavbar /> </div> <div v-for="tasks in APIData" :key="tasks.id" class="container"> <div class="card" style="width: 18rem;"> <div class="card-body"> <h5 class="card-title">{{tasks.task}}</h5> <p class="card-text">{{tasks.details}}</p> <a href="#" class="btn btn-primary">Go somewhere</a> </div> </div> </div> </template> <script> import { getAPI } from '../axios-api' import BaseNavbar from '../components/BaseNavbar.vue' export default { name: 'GetTasks', data () { return { APIData: [] } }, components: { BaseNavbar, }, created () { getAPI.get('/tasks/',) .then(response => { console.log('Task API has recieved data') this.APIData = response.APIData }) .catch(err => { console.log(err) }) } } </script> Django model class Tasks(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) task = models.CharField(max_length=200) details = models.CharField(max_length=500) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateField(auto_now=True) -
How can I solve this path error in project 'not a valid python path'
Hi guys I tried recently to create a new django project. So I run 'pipenv install django'. And this was the error I had. File "C:\Users\KONLAN\AppData\Local\Programs\Python\Python310\Lib\site-packages\pipenv\vendor\pythonfinder\models\python.py", line 379, in getattribute instance_dict = self.parse_executable(executable) File "C:\Users\KONLAN\AppData\Local\Programs\Python\Python310\Lib\site-packages\pipenv\vendor\pythonfinder\models\python.py", line 624, in parse_executable raise ValueError("Not a valid python path: %r" % path) ValueError: Not a valid python path: 'C:/Users/KONLAN/Downloads/Anaconda/python.exe' HOW CAN I SOLVE THIS? -
how to get a good job as a web developer
I graduated a tech school with a Web developer certificate in 2017. I had been doing data analytics using mainly SQL before that. I really enjoy coding the SQL reports, and I enjoy Python as a language. Now I do eCommerce selling tools, and it is kind of a drag. I am not sure what to learn, or where to focus my efforts to earn the most money. Running out of time. I would like to read some suggestions on finding work, or what to learn to find work. Certifications in SQL? Django? -
Why is there no existing virtual environment in setting up Django?
I successfully installed Django but when I type the command pipenv shell I get an error /usr/bin/python3: No module named pipenv.pew so when i also type the command pipenv --venv it says: No virtualenv has been created for this project yet! I'd appreciate your help, thank you! -
Django Javascript preselected value from database
I have a series of drop downs that are dependent upon the one above it. Starting with 'state' then pulls a list of all cities for that state and then all schools in that city. I am trying to find a way that when a user wants to update this information that it will pull the current information from the database and then have that value preselected from the list. Currently it just shows the 'Choose a state' the whole time until selected. If the user is from Maine, I want that to be selected already. Also, if possibly, how to make this an if statement. That if the user's state is null, then 'Choose state' is displayed and if not null, display current state. Thank you very much for the help! views.py def get_json_state_data(request): qs_val_unsorted = list(States.objects.values()) qs_val = sorted(qs_val_unsorted, key=lambda d: d['name']) return JsonResponse({'data':qs_val}) display.html <div class="ui fluid search selection dropdown" id='states_dropdown'> <input type="hidden" name="state"> <i class="dropdown icon"></i> <div class="default text" id="state_text">Choose a state</div> <div class="menu" id='state_data_box'> </div> </div> main.js $.ajax({ type: 'GET', url: '/register/states-json/', success: function(response){ const states_data = response.data states_data.map(item=>{ const option = document.createElement('div') option.textContent = item.name option.setAttribute('class', 'item') option.setAttribute('data_value', item.name) statesDataBox.appendChild(option) }) }, error: function(error){ … -
Set Cache in Django, but a data must dynamically
I have an issue, i want to save data to cache so when i need to get data i dont need it to get from database. But there is a data i need to get from database no matter what which is stock. Illustration i need to save to cache from db: ProductDetails:{ 'product_name': ...., 'categories':...., etc } but the stock product which i need to get is from the same db,i try to use multiple loop like this: ''' products = queryset() cache_key =f'test_detail_{parameter}' information = {} details = [] if not cache.get(cache_key): for product in products: information[product_id] = { 'product_name': product.name, 'date_input': product.date, 'weight':product.weight } cache.set(cache_key, information, duration) information = cache.get(cache_key) for key, value in information.items(): information[key][stock] = numpy.sum([x.stock for x in products if key == x.id ]) details.append(information[key]) return details ''' is there any method more efficient and effective using only 1 Queryset because i'm using 2 Queryset (the first time is when i get the data to set cache, the second time is when i get the stock data)? Thankss -
My VS Code shows false syntax error when I import while writing code for my Django project
My VS Code shows false syntax errors and underlines 'from __ import __ ' types of lines when I import something after writing a few lines of code. I'm doing a Django project and this keeps happening so much. It works after I close and re-open VS Code but that's hectic. I don't know what's causing it or how I can solve it. -
How Do I Get Django Poll Votes In Percentage Format?
I used the tutorial to create a polling app...and I've been expanding on it...I've got it working...but I can't figure out how to turn the votes into percentages... I have tried to do something like... def percentage(self): return 100 * (self.votes) / (self.survey) But this isn't working... My models look like... class Choice(models.Model): choice = models.TextField(max_length=264,blank=True,null=True,unique=False) survey = models.ForeignKey("Survey",on_delete=models.CASCADE,related_name="choice_survey") votes = models.IntegerField(default=0) class Survey(models.Model): survey_name = models.CharField(max_length=255,blank=True,null=True,unique=False) survey_type = models.CharField(choices=STATUS_CHOICES8,blank=True,max_length=300) I've seen examples of annotate and I've played with them as well. Do I need to keep track of the total number of votes as an attribute? The other examples I've seen are all foreignkey. I can totally get the number of votes by getting the integerfield. I just can't seem to figure out how to convert this into a percentage. Thanks in advance for any suggestions.