Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to send emails from Gmail without turning off "allow less secure apps" setting?
Is there any way to send an email in a Django project without turning on the "allow less secure apps" feature? Is using OAuth2 a must or can I send it using Google's API? So far, I just use: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = '587' EMAIL_HOST_USER = 'myemailaddress' EMAIL_HOST_PASSWORD = 'password' EMAIL_USE_TLS = True EMAIL_USE_SSL = False But this gives me an SMTPAuthenticationError, which only works when I turn on "allow less secure apps" in Google. Is there any way to circumvent this without using OAuth2 and allow multiple users to login to that account easily? -
django SearchFilter is displaying all the data when the search field is empty?
I have implemented search feature using django SearchFilter DRF which is perfectly working but the issue is i don't want to display all the query when i pass nothing in the search field .It is by default returning all the query.I don't know how to handle it, here is my code views.py class EventSearchView(generics.ListAPIView): permission_classes = (AllowAny,) queryset = Event.objects.all() search_fields = ["name", "description","content"] filter_backends = (filters.SearchFilter,) serializer_class = EventSearchSerializer pagination_class = LargeResultsSetPagination when i search for fields "name", "description" it is working fine but when i search nothing and hit the url without search fields by default it is returning all the query , but i want to display nothing , how will i achieve that, any help would be appreciated -
How do you call a view from a template(django)
I have an index.html that has three tabs: <div class="tab"> <button class="tablinks" onclick="openCity(event, 'London')" id="defaultOpen"$ <button class="tablinks" onclick="openCity(event, 'Paris')">Paris</button> <button class="tablinks" onclick="openCity(event, 'Tokyo')">Tokyo</button> </div> <div id="London" class='progress-wrapper'> <div id='progress-bar' class='progress-bar' style="background-color: #68a9ef$ </div> <div id="progress-bar-message">Waiting for progress to start...</div> <div id="Paris" class="tabcontent"> <span onclick="this.parentElement.style.display='none'" class="topright">&times</span> <h3>Paris</h3> <p>Paris is the capital of France.</p> </div> <div id="Tokyo" class="tabcontent"> <span onclick="this.parentElement.style.display='none'" class="topright">&times</span> <h3>Tokyo</h3> <p>Tokyo is the capital of Japan.</p> </div> <script> function openCity(evt, cityName) { var i, tabcontent, tablinks; tabcontent = document.getElementsByClassName("tabcontent"); for (i = 0; i < tabcontent.length; i++) { tabcontent[i].style.display = "none"; } tablinks = document.getElementsByClassName("tablinks"); for (i = 0; i < tablinks.length; i++) { tablinks[i].className = tablinks[i].className.replace(" active", ""); } document.getElementById(cityName).style.display = "block"; evt.currentTarget.className += " active"; } // Get the element with id="defaultOpen" and click on it document.getElementById("defaultOpen").click(); </script> </body> <div class='progress-wrapper'> <div id='progress-bar' class='progress-bar' style="background-color: #68a9ef; width: 0%;">&nbsp;</div> </div> <div id="progress-bar-message">Waiting for progress to start...</div> <script src="{% static 'celery_progress/celery_progress.js' %}"></script> <script> document.addEventListener("DOMContentLoaded", function () { var progressUrl = "{% url 'celery_progress:task_status' task_id %}"; CeleryProgressBar.initProgressBar(progressUrl); }); </script> This index.html is loaded by the following in views.py: def index(request): # return HttpResponse('Hello from Python!') # okdood() something = progress_view() #pprint(something) return render(request, "index.html", something) basically what progress_view() does is it … -
Find data inside the nested ORM in Django
class Post(models.Model): POST_TYPE =( ("video","video"), ("pic","pic"), ) upload_by = models.ForeignKey(User,on_delete=models.CASCADE) caption = models.TextField() post_type = models.CharField(max_length=100,choices=POST_TYPE) media = models.FileField(upload_to='posts/') created_at = models.DateTimeField(auto_now_add=True) class PostLikes(models.Model): post = models.ForeignKey(Post,on_delete=models.CASCADE) like_by = models.ForeignKey(User,on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) This is My models.py file and i want to find that if current login user is liked the post or not like this in my templates. I'm doing this in my templates file {% if request.user in i.postlikes_set.all%} but i know it's wrong can anybody solve this problem? I want to do this in my templates <a class="post-like-btn" href="#" {% if request.user in i.postlikes_set.all%} style="color: #e16a70;" {% else %} style="color:#b2b2b2 !important;" {% endif %}> -
How to get the local API url in custom command
I want to call the local API I can access this from wget wget http://localhost:8000/api/item So the code below works get_url_info = requests.get('http://localhost:8000/api/items') print(get_url_info) However, url could be changed depending on server (ex http://localhost:8000/ -> http://localhost/ How should I access to the local API??? -
Module "django.template.context_processors" does not define a "custom_proc" attribute/class
def custom_proc(request): "A context processor that provides 'app', 'user' and 'ip_address'." return { 'app': 'My app', 'user': request.user, 'ip_address': request.META['REMOTE_ADDR'] } above code is my code. a request Context. i write this code in a file context_processors.py. and follow code is in settings.py file: 'context_processors': [ 'django.template.context_processors.custom_proc', how to use the context processor in the view.py file? return render(request,'template1.html', {'message': 'I am view 1.'})``` enter code here -
ValidationError (User:None) (Value must be one of ['U', 'L']: ['qty']) with mongodbforms when using grouped choices
I have a problem with mongodbforms which i've used for mongoengine to generate forms in django Actually i used grouped choices in forms.py from .models import * from mongodbforms import * class UserForm(DocumentForm): gch = ChoiceField(choices=Q_CHOICES, initial='Li') class Meta: document = User fields = ['name', 'email', 'age', 'is_major', 'gch'] If i use like normal choices its working. Q_CHOICES = (('N', 'Num'), ('C', 'Cnt'), ('Li', 'Lit'), ('ML', 'MiL')) This is my model class in models.py Q_CHOICES = ( ('U', (('N', 'Num'), ('C', 'Cnt')) ), ('L', (('Li', 'Lit'), ('ML', 'MiL')) ) ) class User(Document): name = StringField(max_length=50) email = StringField(required=True) is_major = BooleanField(choices=BOOL_CHOICES) age = IntField() gch = StringField(choices=Q_CHOICES) def __str__(self): return self.name What could be the problem ? -
Creating a calendar functionality
I want to create a calendar type functionality in django, where the authenticated user will click on the date of the calendar and he can then write an event or to-do. I want to know about the model making and URL routing. -
How to set the log file size limit for basic config?
In my django, i have create log by using logging.basicConfig(). The output of the log i wish to set the file size limit, after reach the file size limit, it will auto create a new log file, anyone have idea? -
Multiple forms in single forms in Django?
I wanted to build signup form for Student User Where User Can Select Multiple Branches(Model) and select Subjects inside one subject can have multiple books. all this in single form. I have been looking at the documentation and thought maybe inline-formsets would be the answer. But I am not entirely sure. How can i do this in single signup page? I hope you get my point. What I want is I have Total five models class User(AbstractUser): created_date = models.DateTimeField(auto_now_add=True) modified_date = models.DateTimeField(auto_now=True) is_student = models.BooleanField(default=False) is_teacher = models.BooleanField(default=False) class Student(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) age = models.IntField(max_length=100) dob = models.DateField(max_length=12) address = models.CharField(max_length=200) def __str__(self): if (self.user.first_name != None): return self.user.first_name else: return self.user.username class StudentBranch(BaseModel): student = models.ForeignKey(Student, on_delete=models.CASCADE) branch = models.ForeignKey(Branch, on_delete=models.CASCADE) class StudentSubject(BaseModel): student = models.ForeignKey(Student, on_delete=models.CASCADE) subject = models.ForeignKey(Subject, on_delete=models.CASCADE) class SubjectBook(BaseModel): subject_name = models.ForeignKey(StudentSubject, on_delete=models.CASCADE) book_name = models.CharField(max_length=100, blank=True) author = models.CharField(max_length=100, blank=True) publisher = models.CharField(max_length=100, blank=True) published_in = models.CharField(max_length=10, blank=True) I tried some examples with 2 models but in my case i have many models -
Accurate progress bars to load tweets from twitter
I'm trying to load tweets from the user timeline in twitter and display a progress bar while doing so. In order to use the progress bar, you have to know that amount of 'work' that needs to be done to complete the task. The problem is, the count that you specify in GetUserTimeline is not necessarily the number of tweets that is returned to the call(on account of deleted tweets and so forth the amount of tweets returned maybe less). This means that you can't calculate the number of calls that have to be made to the Twitter API to achieve your target number of retrieved tweets, without loading the tweets beforehand. Can anyone think of a solution?? -
Highcharts do not show in Django html
I am trying to show some data plot in web, the web framework is Django, I pass the json data form view to html, the json file is like below { 'my_data':[1, 2, 3, 10, 15, 18, 19] 'pointStart':1350230400 'pointInterval': 3600*1000*24 } and the html body part is below <body> <div id="container1" style="height: 400px; min-width: 310px"></div> <script> // Create a timer var start = +new Date(); // Create the chart Highcharts.stockChart('container1', { chart: { events: { load: function () { if (!window.TestController) { this.setTitle(null, { text: 'Built chart in ' + (new Date() - start) + 'ms' }); } } }, zoomType: 'x' }, rangeSelector: { buttons: [{ type: 'day', count: 3, text: '3d' }, { type: 'week', count: 1, text: '1w' }, { type: 'month', count: 1, text: '1m' }, { type: 'month', count: 6, text: '6m' }, { type: 'year', count: 1, text: '1y' }, { type: 'all', text: 'All' }], selected: 3 }, yAxis: { title: { text: 'Temperature (°C)' } }, title: { text: 'Hourly temperatures in Vik i Sogn, Norway, 2009-2017' }, subtitle: { text: 'Built chart in ...' // dummy text to reserve space for dynamic subtitle }, series: [{ name: 'Temperature', data: {{my_data}}, … -
Django Model with out auto generated id field
Model.py Image -- Migrate Query basically a "product(Rodamiento)" can have one, none or many "equivalents(Equivalente)" when i create the "equivalent" class, django auto generate an "id" field. ¿is there a way to avoid that?, i need to transfer data from another DB, that "id" field make it harder to do it im using SQLite DB and SQLiteStudio -
template rendering error and near ")": syntax error when i try to access polls app
My problem is I keep getting a weird error during template rendering error form my index.html template point at my {% if latest_question_list %} and I do not know what is triggering the ")" error in my index template except for the base.py and utils.py files. I don't know what is causing the problem and I appreciate any help as I try to step through this as well. I am have been learning Django for python and I have been trying to follow along with the tutorial. This is my first time posting on stackoverflow and I will try to show all my errors and the traceback. I tried googling the errors I get in the traceback of the code but all i get are errors related to sql migrations but I made no changes to my models. P.S: I can give more and edit if not clear or need more info. views.py from django.http import HttpResponseRedirect from django.shortcuts import render, get_object_or_404 from django.template import loader from django.urls import reverse from django.views import generic from django.utils import timezone from .models import Question, Choice class IndexView(generic.ListView): template_name = 'polls/index.html' context_object_name = 'latest_question_list' def get_queryset(self): """ Return the last five published questions.""" … -
How can I get a members list in a voice channel from my bot?
from django.shortcuts import render, redirect import discord import random from discord.ext import commands client = commands.Bot(command_prefix = '.') channel = None @client.event async def on_ready(): channel = client.get_channel(677999369642836037) async def members_list(request): curMembers = [] for member in channel.members: curMembers.append(member) return render(request, "discordTool/discordTool.html", { 'members_list': curMembers, }) client.run('my token') This is my views.py of an app that supposes to show active members in a voice channel in my django site. However this doesn't work, can anyone help me or know a discord server about discord's API? -
How to load CSS files and javascript files in Django?
When I am trying to extend the header and footer of base.html to index.html and about.html, I am unable to load CSS and javascript files. Here is my code. I have Included django.contrib.staticfiles in INSTALLED_APPS. Also, I have defined STATIC_URL setting.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'gadget/static') ] I am trying to extend the header and footer to index.html and about.html base.html {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <link href="https://fonts.googleapis.com/css?family=Muli:300,400,500,600,700,800,900&display=swap" rel="stylesheet"> <!-- Css Styles--> <link rel="stylesheet" type="text/css" href="{% static 'css/bootstrap.min.css'%}" /> <link rel="stylesheet" type="text/css" href="{% static 'css/font-awesome.min.css'%}" /> <link rel="stylesheet" type="text/css" href="{% static 'css/themify-icons.css'%}" /> <link rel="stylesheet" type="text/css" href="{% static 'css/elegant-icons.css'%}" /> <link rel="stylesheet" type="text/css" href="{% static 'css/owl.carousel.min.css'%}" /> <link rel="stylesheet" type="text/css" href="{% static 'css/nice-select.css'%}" /> <link rel="stylesheet" type="text/css" href="{% static 'css/jquery-ui.min.css'%}" /> <link rel="stylesheet" type="text/css" href="{% static 'css/slicknav.min.css'%}" /> <link rel="stylesheet" type="text/css" href="{% static 'css/style.css'%}" /> <title>e-Gadget</title> </head> <body> <!-- Header Section Begin --> <header class="header-section"> <div class="container"> <div class="inner-header"> <div class="row"> <div class="col-lg-2 col-md-2"> <div class="logo"> <a href="./index.html"> <img src="img/logo.png" alt=""> </a> </div> </div> <div class="col-lg-7 col-md-7"> <div class="advanced-search"> <button … -
Reload table data in Django automatically
I am trying to solve an issue regarding reloading table data in Django without refreshing the page. I was experimenting with this example but I am having a difficult time to modify it to my needs. I liked the solution but I wonder if there is any other way? If not, I will need to try that approach, but it was harder than I thought to modify it. My view def test(request): data = data.objects.all().order_by('-created') context = { 'data':data } return render(request, 'app/html.html', context) My original HTML-table <table class="table table-sm table-hover table-striped" id="myTable"> <thead class="thead-dark"> <tr> <th scope="col">Column1</th> <th scope="col">Column2</th> <th scope="col">Column3</th> </tr> </thead> <tbody id="tableBody"> {% for product in data %} <tr> <td>{{ product.name }}</td> <td>{{ product.price }}</td> <td>{{ product.country }}</td> </tr> {% endfor %} </tbody> </table> Thanks in advance -
django-rest-auth redirects settings not working as expected
I am using django-rest-auth and django-allauth to handle user authentication in my rest api. The issue is the redirects are not working as expected. I expect that If the user is logged in, when I try to access the login or signup page it should redirect me to whatever the settings.LOGIN_REDIRECT_URL is. What actually happens is, the user does not get redirected I also expect, that when clicking the link to verify the email, when it validates, the website should redirect to a success page as specified in the settings.py as ACCOUNT_EMAIL_CONFIRMATION_AUTHENTICATED_REDIRECT_URL = "api/authsuccess" What actually happens is, the user the specified redirect link gets added to the end of the confirmation link as http://127.0.0.1:8000/api/signup/account-confirm-email/MTA:1j2lIk:T9uOHxOu395ZVvCDt41ylFnysIw/api/authsuccess. the api/authsuccess gets added to the end of the link which is not a behavior I expect. below are the major settings in my app OLD_PASSWORD_FIELD_ENABLED = True ACCOUNT_LOGOUT_ON_PASSWORD_CHANGE = False LOGOUT_ON_PASSWORD_CHANGE = False ACCOUNT_USER_MODEL_USERNAME_FIELD = None ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_USERNAME_REQUIRED = False ACCOUNT_AUTHENTICATION_METHOD = 'email' ACCOUNT_USER_EMAIL_FIELD = 'email' ACCOUNT_UNIQUE_EMAIL = True ACCOUNT_SESSION_REMEMBER = True ACCOUNT_LOGOUT_ON_GET = True ACCOUNT_EMAIL_VERIFICATION = "mandatory" ACCOUNT_CONFIRM_EMAIL_ON_GET = True ACCOUNT_AUTHENTICATED_LOGIN_REDIRECTS =True LOGIN_REDIRECT_URL = "api/user" ACCOUNT_EMAIL_CONFIRMATION_AUTHENTICATED_REDIRECT_URL = "api/authsuccess" ACCOUNT_LOGIN_ON_EMAIL_CONFIRMATION = True ACCOUNT_EMAIL_CONFIRMATION_EXPIRE_DAYS = 2 ACCOUNT_EMAIL_CONFIRMATION_HMAC =True ACCOUNT_LOGIN_ATTEMPTS_LIMIT = 5 ACCOUNT_LOGIN_ATTEMPTS_TIMEOUT = … -
Margin left, right etc. not working for individual select options in bootstrap select
I have a bootstrap select field, with some options disabled, I would like to move all the disabled options to the left end except for the "Select" option. this is my html code: <div class="form-group"> <label class="col-md-6">VType</label> <select class="selectpicker col-md-6" name="veh" id="veh" onchange="hideShow()" required> <option value="" disabled selected>Select</option> <option disabled id="sl">SL</option> <option id="ve2" value="A">A</option> <option id="ve3" value="B">B</option> <option id="ve4" value="C"> C </option> <option id="ve5" value="D">D</option> <option id="ve6" value="E"> E </option> <option id="ve7" value="F">F</option> <option disabled id="ll"><b>LL</b></option> <option id="ve8" value="G">G</option> <option id="ve9" value="H">H</option> <option id="ve10" value="I">I</option> <option id="ve11" value="J">J</option> <option id="ve12" value="K">K</option> <option disabled id="tat"><b>TAT</b></option> <option id="ve13" value="L">L</option> <option id="ve14" value="M">M</option> <option id="ve15" value="N">N</option> <option disabled id="BS"><b>BS</b></option> <option id="ve16" value="O">O</option> <option id="ve17" value="P">P</option> <option id="ve18" value="Q">Q</option> <option disabled id="sut"><b>SUT</b></option> <option id="ve19" value="R">R</option> <option disabled id="ct"><b>CT</b></option> <option id="ve20" value="S">S</option> <option id="ve21" value="T">T</option> </select> </div> This is my CSS #sl{ margin-left: -10%; } I've also tried with the select id and option id as follows: #veh #sl{ margin-left: -10%; } How do I make this possible? -
Django python View and Form - MultiValueDictKeyError at /result 'num1' - Why will my form not submit data
I've created a form to add two numbers and receive MultiValueDictKeyError at /result 'num1'. I've tried many things but can't figure it out. I figured I'd give this a try. project url.py: """ from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static from datetime import datetime urlpatterns = [ path('admin/', admin.site.urls), path('', include('app1.urls')), path('result', include('app1.urls')), ] urlpatterns = urlpatterns + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) App url.py: from django.urls import path, include from django.conf.urls import include, url from django.conf import settings from django.conf.urls.static import static from . import views from . import urls from app1.models import Footprint import app1.views urlpatterns = [ path("", views.index, name="index"), path('result', views.calc, name='result'), ] views.py: from django.shortcuts import render from django.http import HttpResponse from django.http import HttpRequest,HttpResponseRedirect from .models import Footprint # Create your views here. def index(request): foots = Footprint.objects.all() return render(request, "index.html", {'foots': foots}) def calc(request): val1 = int(request.POST['num1']) val2 = int(request.POST['num2']) res = val1 + val2 return render(request,'result.html',{'result': res}) Form from index.html file: block content %} <form action="calc" method="post"> {% csrf_token %} <p style="color:white;">Installation Cost:</p> <input type="text" name="num1"> <p style="color:white;">Installation Year:</p> <input type="text" name="num2"><br><br> <p><a href="result" class="btn btn-primary btn-lg btn-custom">SUBMIT</a></p> </form> {% endblock %} result.html: {% block … -
How change the Connection Arguments (after, before) in graphene-python (relay)?
Using: Django 3.x [ Django-Filters 2.2.0, graphene-django 2.8.0, graphql-relay 2.0.1 ] Vue 2.x [ Vue-Apollo ] After applying some filters (iContains etc.) on my graphQL search i tried to change or manipulate the connection_args like firstor after. I can fetch a Dictionary on my resolver like {'first': 2, 'name__icontains': 'eagle'} with values i put in the IDE. As you can see (Example 1 /def resolve_all_birds2) i use that already for a logic. But i do not understand where do manipulate the GraphQLArgument states of the before. after first. last function which comes with relay? Example 1 class ExtendedConnection(Connection): class Meta: abstract = True total_count = Int() edge_count = Int() def resolve_total_count(root, info, **kwargs): return root.length def resolve_edge_count(root, info, **kwargs): return len(root.edges) class Birds2Node(DjangoObjectType): class Meta: model = Birds filter_fields = { 'id': ['exact', 'icontains'], 'name': ['exact', 'icontains', 'istartswith', 'iendswith'], } interfaces = (relay.Node, ) connection_class = ExtendedConnection # --- CUSTOM FIELDS --> # pkey = _db primary key pKey = Int() def resolve_pKey(parent, info): return parent.pk # qRank = Item Rank in Edge Array qRank = Int() def resolve_qRank(parent, info, **kwargs): return info.path[2] class Birds2Query(ObjectType): birds2 = relay.Node.Field(Birds2Node) all_birds2 = DjangoFilterConnectionField(Birds2Node) def resolve_all_birds2(self, info, **kwargs): if 'name__icontains' in kwargs: nameIcon … -
Django Add Choices Directly From Admin Not Working
When I try to add a subject from admin into the Subject model's name field, I am getting an error when I try to save the entry (see admin image below). I'm using the latest Django 3 and Python 3. This code used to work with Django 2 but since the upgrade, it does not populate anything into a blank SUBJECT_CHOICES() from admin. What I want to do is directly add subjects from admin into the database so that these subjects will populate the subjects dropdown menu in my forms.py. In other words, I want my dropdown menu from forms.py for the subjects to populate all of the subjects that I add directly from admin (see image below for an example dropdown menu with all the subjects entered). I see two different ways of solving this but I am unsure how to code them. Either just use a ForeignKey with SubjectName model, or a simple CharField without choice and customize the input widget into a dropdown. I might still need something custom for the form if I were to have dropdown-select and also type-in new choice from admin. Models.py: from django.db import models from django.urls import reverse from memberships.models import … -
Filter inheritance django and graphene
im trying to use django-graphene and having hard time to filter by foreign key's fields. class Country(SupplierProduct): name = models.CharField(max_length=100) class City(SupplierProduct): name = models.CharField(max_length=100) country = models.ForeignKey(Country, on_delete=models.CASCADE) class Location(models.Model): city = models.ForeignKey(City, on_delete=models.CASCADE) street = models.CharField(max_length=200) number = models.IntegerField('House Number') class Hotel(SupplierProduct): name = models.CharField('hotel name', max_length=500) rate = models.IntegerField('number of stars') location = models.ForeignKey(Location, on_delete=models.CASCADE) and i'm trying to make queries easier by renaming fields and create my own Filter Class. class LocationFilter(df.FilterSet): country_name = df.CharFilter(field_name='city__country__name', lookup_expr='icontains') city_name = df.CharFilter(field_name='city__name', lookup_expr='icontains') class Meta: model = Location fields = ['country_name', 'city_name'] now i wanted to know if there is a way for me to make hotel's filter class to use this filter also for its location field? like somekind of inheritance that every model that has location in it could filter easily by its fields -
Template shows custom ModelForm but data is not being saved through views.py
I'm trying to build a book-tracker app where users can login and submit books they've read and rate each book on a 5-star scale. I'm using 2 forms and they show up in the template home.html, but I'm not sure how to pass that data through in views.py and save it in the database. The HomeForm data is saved, but RatingForm data is not. forms.py: from django import forms from home.models import Post, Rating class HomeForm(forms.ModelForm): post = forms.CharField() rating = forms.IntegerField() class Meta: model = Post fields = ( 'book_title', 'book_author', 'book_review', ) class RatingForm(forms.ModelForm): rating = forms.IntegerField() class Meta: model = Rating fields = ( 'stars', ) views.py: from django.views.generic import TemplateView from home.forms import HomeForm, RatingForm from django.shortcuts import render, redirect from home.models import Post, Rating class HomeView(TemplateView): template_name = 'home/home.html' def get(self, request): form = HomeForm() rating_form = RatingForm() posts = Post.objects.all() args= {'form': form, 'posts': posts, 'rating_form': rating_form,} return render(request, self.template_name, args) def post(self, request): form_a = HomeForm(request.POST, prefix='home') form_b = RatingForm(request.POST, prefix='rating') if form_a.is_valid() and form_b.is_valid(): post = form_a.save(commit=False) rating = form_b.save(commit=False) text = form_a.cleaned_data['post'] post.user = request.user post.save() rating.user = request.user rating.save() rate = form_b.cleaned_data['stars'] return redirect('home') args = {'form_a': form_a, 'form_b': form_b, … -
Counting 2 Querysets Deep within Django Template
Is there a way to count within a Django template on a 2nd deep queryset connected via FK's/M2M's? For instance, Model A is FK'd to Model B, and Model B is M2M'd to Model C {% for C in Cs %} {% for B in C %) {% if B.A.all.count >= 2 %} B Has multiple A's! {% else %} B only has 1 A! {% endif %} {% endfor %} {% endfor %} Basically, I want to count the number of A's within B, and if it's 2 or more, just display "Multiple," as actually listing them out is disrupting my template. But I can't seem to get it to work. At the same time, the below DOES work for me: {% for C in Cs %} {% if C.B.all.count >= 2 %} C has multiple B's! {% else %} C only has 1 B! {% endif %} {% endfor %} I just can't get it to go one queryset deeper. Any help? Do I have to do this within the views?