Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ValueError: not enough values to unpack (expected 4, got 3) using Django
using Django check_password() got this error, in database i have stored using hashed password using make_password() imported required statements from django.contrib.auth.hashers import make_password,check_password line giving error is password = check_password(pas, fetchRes[0][3]) here is my code def signin(request): res="" login_failed = False conn = sql.connect(host="localhost",user="root",password="",database="agroxpert") cur = conn.cursor() if request.method=="POST": met=request.POST aid=met['aid'] pas=met['pas'] inp=(aid,) cur.execute('''SELECT * from admin where AID=%s''',inp) fetchRes = cur.fetchall() password = check_password(pas, fetchRes[0][3]) if password and len(fetchRes) == 1: request.session['FID']=aid login_failed = False conn.commit() conn.close() return HttpResponseRedirect('administration/') else: login_failed = True res = "Unable to Signin Password or Admin Id entered is incorrect" print(res) return render(request,'admin.html',{"res":res,"failed":login_failed}) -
How to get count value of a ManyToManyField?
I have a model Post with a ManyToManyField field "User": class Post(models.Model): STATIC_CHOICES = ( ('draft', 'Draft'), ('published', 'Published') ) title = models.CharField(max_length = 255) slug = models.SlugField(max_length = 255) author = models.ForeignKey(User, related_name = 'blog_posts', on_delete = models.CASCADE) body = models.TextField() likes = models.ManyToManyField(User, related_name = 'likes', blank = True) upvotes = models.IntegerField(default = 0) created = models.DateTimeField(auto_now_add = True) status = models.CharField(max_length = 10, choices = STATIC_CHOICES, default = 'draft') def __str__(self): return self.title def total_likes(self): return self.likes.count() def get_absolute_url(self): return reverse("post_detail", args=[self.id, self.slug]) I understand that the method total_likes()returns the number of likes in the views. However, I want to display the number of likes in the upvotesIntegerField's default value. Basically, if I could do something like: upvotes = models.IntegerField(default = total_likes()) so that the number of likes show up as the default value in the IntegerField in the admin. However, since I cannot do that, what is the best way so that I can get the number of likes to show up in the IntegerField in upvotes? -
Error: UPGRADE FAILED: another operation (install/upgrade/rollback) is in progress
I am using helm upgrade xyz --install command and my release were failing due to other helm issues. So no successful release is done yet. Then one time when the above command was in progress, I pressed ctrl+c command. And since then it is showing Error: UPGRADE FAILED: another operation (install/upgrade/rollback) is in progress whenever I try helm upgrade again. When i do helm history helm history xyz It shows Error: release: not found. No I don't know how to roll back the previous operation so that I can try helm upgrade again. I tried --force too helm upgrade xyz --install --force but it is still showing some operation is in progress. So how can I roll back the previous process when I don't have any successful release. -
Django Email Template for loop not working
Im working with Django HTML Email. The list of data is working when I print() using terminal but when I call in email template, only the 1st data display in Html Email. I tried to run in Localhost everything is working even the for loop all data display in form of list. Please help me to figure out what are missing or wrong in my script.Thank You! After sending email, this is the email output, only the First data got listed This is the data that I want to display In Email Template send email script class HomeView(ListView): month = datetime.datetime.now().month elif month == 4: cstatus = vehicleData.objects.filter( Registration_month="APR", sent_email="No") s = "" for carreg in cstatus: print(carreg.PLATE_NO) s = carreg.PLATE_NO print(s) cstatus.update(sent_email="No") if s != "": subject = 'Sample' html_message = render_to_string('email.html', {'content':s}) plain_message = strip_tags(html_message) from_email = 'From <sampleemail@gmail.com>' to = 'sampleemail@gmail.com' mail.send_mail(subject, plain_message, from_email, [to], html_message=html_message,fail_silently=False) Template <body> <h2>Hi,</h2> <p> Please update before month End!</p> <ul> {% for vehicle in content %} <li>{{ vehicle }}</li> {% endfor %} </ul> </body> -
How can i share data between two tenants, like contacts list
i'm working on a small project using Django and i'm using Django tenancy Schemas, i need a help about sharing data between users, i found that can someone explain to me the role of with schema_context from tenant_schemas.utils import schema_context with schema_context(schema_name): is that make sense in my situation ? to solve my need ( sharing data between tenants ) -
Customize Django Log Entry Change_Message Field with the 3 Action Flags
Basically, I want to customize the change_message to make it more friendly, and show something in deletion action flag. Any approaches? image -
Markdownify; template won't wrap string
I'm using Markdownify (django-markdownify) to convert the markdown content from a user form into HTML. Yet I've encountered a bug of sorts where a long string with no whitespace is supplied. The subject string will not wrap in the container of a certain width of which {{ markdownify }} is inserted. However if strings with whitespace are provided they in fact do wrap. Has anyone using markdownify encountered this before? How would this be resolved so that strings as 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' wrap as expected? The string with the white space demonstrates the expected behavior. The markdown library is installed in INSTALLED_APPS. MARKDOWNIFY = { 'default': { 'WHITELIST_TAGS': [ 'a', 'abbr', 'acronym', 'b', 'blockquote', 'code', 'em', 'i', 'li', 'ol', 'strong', 'ul', 'pre', 'p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6' ], "MARKDOWN_EXTENSIONS": [ 'markdown.extensions.fenced_code', 'markdown.extensions.extra', ] } } {% load markdownify %} <div class="featured_content"> <div class="response_container"> {{ answer.response|markdownify }} </div> </div> -
django-admin site display problem in different port
I got a very confused problem. When I use port 8000 to run my django project. The django-admin site display normal. However, when I use port 80 to run my django project. The django-admin site display a little different in page layout. Such as the positions and size of the search bar and the form are different. They both can load the css and no error comes out -
why the django static file not loading
settings.py import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = 'j2-%r(!2*(3$(j96or3h23cp(+5%c!1&v+z9(%-v-9%pr*sdtx' DEBUG = True ALLOWED_HOSTS = [] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'authn', ] 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 = 'first.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 = 'first.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'djongo', 'NAME': 'login', } } AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True STATIC_URL = '/static/' STATICFILES_DIRS=[ os.path.join(BASE_DIR,'static') ] files location urls.py from django.contrib import admin from django.urls import path from django.conf.urls.static import static from . import views urlpatterns = [ path('',views.home,name="home"), path('register/', views.registerPage, name="register"), path('login/', views.loginPage, name="login"), path('logout/', views.logoutUser, name="logout"), ] html file i am trying to work on <head> <title>Nura Admin - Charts</title> <meta name="description" content="Charts | Nura Admin"> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="author" content="Your website"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <!-- Favicon --> <link rel="shortcut icon" href= "{% static 'assets/images/atomic.png'%}"> <!-- Bootstrap CSS --> <link href="{% static 'assets/css/bootstrap.min.css'%}" … -
How do I fix "POST http://127.0.0.1:8000/admin/auth/user/ net::ERR_CONNECTION_REFUSED" error in Vue project?
I'm making a Vue project and, when making an axios.post call in my vue file, I get POST http://127.0.0.1:8000/admin/auth/user/ net::ERR_CONNECTION_REFUSED as an error on the site and a Uncaught (in promise) Error: Network Error at createError (createError.js?2d83:16) at XMLHttpRequest.handleError (xhr.js?b50d:84) error right after. The login method I'm attempting to use that's giving the errors: login() { axios.post('http://127.0.0.1:8000/admin/auth/user/', { username: this.username, password: this.password, }) .then(resp => { this.token = resp.data.token; console.log(this.token) localStorage.setItem('user-token', resp.data.token) }) } The full error: POST http://127.0.0.1:8000/admin/auth/user/ net::ERR_CONNECTION_REFUSED dispatchXhrRequest @ xhr.js?b50d:177 xhrAdapter @ xhr.js?b50d:13 dispatchRequest @ dispatchRequest.js?5270:52 Promise.then (async) request @ Axios.js?0a06:61 Axios.<computed> @ Axios.js?0a06:87 wrap @ bind.js?1d2b:9 login @ Header.vue?0418:44 $data.token.Object.onClick._cache.<computed>._cache.<computed> @ Header.vue?0418:17 callWithErrorHandling @ runtime-core.esm-bundler.js?5c40:154 callWithAsyncErrorHandling @ runtime-core.esm-bundler.js?5c40:163 invoker @ runtime-dom.esm-bundler.js?830f:333 I've looked around in Django documentation and around stackoverflow for a couple hours and haven't found any solutions. Any assistance, critiques, comments, or questions would be appreciated. I'd be more than happy to provide any additional information needed. -
Cannot extend a tamplate in Django
I have a following template: {% load i18n %} {% load static %} <!DOCTYPE html> <html> <head> <title>{% translate "login page" %}</title> <link rel="stylesheet" type="text/css" href="{% static 'taskmanager/style/authpages.css' %}"> </head> <body> {% block testblock %} {% endblock testblock %} <form method="post" action="{% url 'login' %}" class="main-form"> {% csrf_token %} <label for="username">{% translate "User name: " %}</label> {{ form.username }} {{ form.username.errors }} <label for="password">{% translate "Password: " %} </label> {{ form.password }} {{ form.password.errors }} {% if form.errors %} {{ form.non_field_errors }} {% endif %} <input type="submit" value="{% translate 'sign in' %}"> <input type="hidden" name="next" value="{{ next }}"> <a href="{% url 'register' %}">{% translate "Register" %}</a> </form> {% block switch_lang_button %} {% endblock switch_lang_button %} </body> </html> and also I have a template to extend it: {% extends "registration/login.html" %} {% block testblock %} <div> testblock content </div> {% endblock testblock %} template settings in settings.py is standard and was not changed: 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', ], }, }, ] It seems to me that everything I have done is consistent with the documentation and I cannot figure out which of these is not working. I … -
Django How to display data from a view context inside a formset
Let's say I have a django template that contains the following form: {% if evidence_formset %} <form id="evidence-formset" action="{% url 'variants:interpret-criteria' %}" method="post"> <div class="form-group row mt-3 justify-content-between"> <!-- I would like to display my content here --> </div> <div class="form-group row mt-3 justify-content-between"> <div class="col-auto"> <ul class="nav nav-pills" id="evidence-formset-tab" role="tablist"> {% for evidence_form in evidence_formset %} {% with index=forloop.counter|stringformat:'s' %} {% with id='evidence-form-'|add:index|add:'-tab' href='#evidence-form-'|add:index aria_controls='evidence-form-'|add:index %} <li class="nav-item"> {% if not current_tab and forloop.first or current_tab == index %} <a class="nav-link active" id="{{ id }}" data-toggle="pill" href="{{ href }}" role="tab" aria-controls="{{ aria_controls }}" aria-selected="true">{{ forloop.counter }}</a> {% else %} <a class="nav-link" id="{{ id }}" data-toggle="pill" href="{{ href }}" role="tab" aria-controls="{{ aria_controls }}" aria-selected="false">{{ forloop.counter }}</a> {% endif %} </li> {% endwith %} {% endwith %} {% endfor %} </ul> </div> </div> {% csrf_token %} {{ evidence_formset.management_form }} <input type="hidden" name="current_tab" value="{{ current_tab }}" /> <div class="tab-content" id="evidence-formset-tabContent"> {% for evidence_form in evidence_formset %} {% with index=forloop.counter|stringformat:'s' %} {% with id='evidence-form-'|add:index aria_labelledby='evidence-form-'|add:index|add:'-tab' %} {% if not current_tab and forloop.first or current_tab == index %} <div class="tab-pane fade show active" id="{{ id }}" role="tabpanel" aria-labelledby="{{ aria_labelledby }}"> {% include "variants/interpretation_form.html" %} </div> {% else %} <div class="tab-pane fade" id="{{ id }}" … -
How to detect if a Tiktok account has liked a video/post in Python?
I've been working on a project has a feature that needs to check if a user has liked a post(video, which I already have detail about this post). I'm using this https://github.com/davidteather/TikTok-Api but seems like doesn't work. Thank you all in advance, -
Get current logged in user in JSON Format from views.py
I'm trying to build a follow and unfollow button, I want to show the button only For any other user who is signed in, a user should not be able to follow themselves. How can I return from my views.py the currently logged-in user as a JSON format to my JS file? I'm building the button in the JavaScript file and not in the template, I tried to return as JSON format but didn't succeed views.py def display_profile(request, profile): try: profile_to_display = User.objects.get(username=profile) profile_to_display_id = User.objects.get(pk=profile_to_display.id) except User.DoesNotExist: return JsonResponse({"error": "Profile not found."}, status=404) # Return profile contents if request.method == "GET": return JsonResponse(profile_to_display.profile.serialize(), safe=False) else: return JsonResponse({ "error": "GET or PUT request required." }, status=400) models.py from django.contrib.auth.models import AbstractUser from django.db import models class User(AbstractUser): pass class NewPost(models.Model): poster = models.ForeignKey("User", on_delete=models.PROTECT, related_name="posts_posted") description = models.TextField() date_added = models.DateTimeField(auto_now_add=True) likes = models.IntegerField(default=0) def serialize(self): return { "id": self.id, "poster": self.poster.username, "description": self.description, "date_added": self.date_added.strftime("%b %d %Y, %I:%M %p"), "likes": self.likes } class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) following = models.ManyToManyField(User, blank=True, related_name="following") followers = models.ManyToManyField(User, blank=True, related_name="followers") def serialize(self): return { "profileID": self.user.id, "following": int(self.following.all().count()), "followers": int(self.followers.all().count()), } index.js function load_user_info(user_clicked_on){ document.querySelector('#page-view').style.display = 'none'; document.querySelector('#posts-view').style.display = 'none'; document.querySelector('#show-posts').style.display … -
use drf with django_auth_ldap
I use django_auth_ldap with the Django Restframework. But, sometimes I get a HTTP 401 error. sometimes I can get a jwt token. I do not know which problem cause that. Is there anybody can help me. enter image description here enter image description here enter image description here enter image description here -
How to get django-all auth to pass data to custom user model
I'm making a site in Django using django-allauth for authentication. I've created a custom user class in account.models to add a custom field, UserExtraFiledSignup , i have added image field so user can upload profile photo for his account during signup but i got issue The issue I have is that the when user create account and upload photo Actually it's don't uploaded i don't know what is the error my app | models.py : class UserExtraFiledSignup(models.Model): Profile_photo = models.ImageField(default='', upload_to='images/') def save(self, *args, **kwargs): super(UserExtraFiledSignup, self).save(*args, **kwargs) my app | forms.py : from allauth.account.forms import SignupForm from .models import User from blog_app.models import UserExtraFiledSignup from django.contrib.auth import get_user_model class CustomSignupForm(SignupForm): first_name = forms.CharField(required=True,label='First Name',widget=forms.TextInput(attrs={'class': 'form-control','placeholder':' Enter First Name '}) ) last_name = forms.CharField(required=True,label='Last Name',widget=forms.TextInput(attrs={'class': 'form-control','placeholder':' Enter Second Name '}) ) Profile_photo = forms.ImageField(label='Profile photo') class Meta: model = get_user_model() def signup(self, request, user): user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] user.Profile_photo = self.cleaned_data['Profile_photo'] user.save() return user my app | adapters.py : from django.conf import settings from allauth.account.adapter import DefaultAccountAdapter class AccountAdapter(DefaultAccountAdapter): def save_user(self, request, user, form, commit=False): data = form.cleaned_data user.first_name = data['first_name'] user.last_name = data['last_name'] user.Profile_photo = data['Profile_photo'] if 'password1' in data: user.set_password(data['password1']) else: user.set_unusable_password() self.populate_username(request, user) user.save() return … -
How to remove the margins added by bootstrap
Im working on a page utilizing django that has a navbar plus a 3x3 grid that fills the rest of the page. My issue is when I add the bootstrap style-sheet (above my custom style-sheet) i get some white space on the right and the left of both the grid and the navbar. I assume this can be overridden by a custom style-sheet but as im learning I cant figure it out. Following advice from other posts I have messed around a lot with trying to override box-sizing (which changes nothing) and margins (which sticks everything to one side or the other but wont stretch to both sides). I assume something is constraining the size of .container but I dont know. I have used inspect element to try to isolate the problem but no luck. Here the css that works when I exclude the bootstrap stylesheet. /* Master styles*/ body { margin: 0px; font-family: 'Fira Sans', sans-serif; } .container { display: grid; grid-template-columns: 1fr; } /* Nav styles*/ #cart-icon{ width:50px; display: inline-block; margin-left: 15px; } #cart-total{ display: block; position: absolute; top: 10px; right: 20px; text-align: center; color:#fff; background-color: red; width: 18px; height: 18px; border-radius: 50%; font-size: 14px; } .nav-wrapper { … -
How to count a a filtered result in Django?
I'm so far able to get a QuerySet of what I want, but I can't however include the .count() statement in there. I do know I could use len(students) here but I'd like to stick to the Django ORM. student_count = Student.objects.filter(last_online__range=[last week, this week]) How to do it? -
How do I filter a model field case insensitive and unaccent?
I need to make a query that return results ignoring case and accents. Example: I search for 'atacadao' and as a possible answer would be Atacadão, atacadão, Atacadao and atacadao. -
return Database.Cursor.execute(self, query, params) django.db.utils.ProgrammingError: Cannot operate on a closed cursor
from django.db import connection from EmployeeData.models import markAttendance def markAttendance(Name,inTime,InDate): with connection.cursor() as cursor: sql = '''INSERT INTO markAttendance(Name,inTime,InDate) VALUES(%s, %s, %s)''' val=(Name,inTime,InDate) cursor.execute(sql,val) connection.commit() -
Error Django Multiples Values for keyword argument
Can someone please help me? I'm trying to do a simple django api and it's not working really well, I keep having this error: django.db.models.manager.BaseManager._get_queryset_methods..create_method..manager_method() got multiple values for keyword argument 'group' my models are: class Group(models.Model): name = models.CharField(max_length=255) scientific_name = models.TextField() class Characteristic(models.Model): characteristic = models.TextField() class Animal(models.Model): name = models.CharField(max_length=255) age = models.FloatField() weight = models.FloatField() sex = models.CharField(max_length=255) group = models.ForeignKey(Group, on_delete=models.CASCADE) characteristics = models.ManyToManyField(Characteristic) and my serializers: class GroupSerializer(serializers.Serializer): id = serializers.IntegerField(required=False, read_only=True) name = serializers.CharField() scientific_name = serializers.CharField() class CharacteristicsSerializers(serializers.Serializer): id = serializers.IntegerField(required=False, read_only=True) characteristic = serializers.CharField() class Meta: model = Characteristic fields = ('characteristic') class AnimalSerializer(serializers.Serializer): id = serializers.IntegerField(required=False, read_only=True) name = serializers.CharField() age = serializers.FloatField() weight = serializers.FloatField() sex = serializers.CharField() group = GroupSerializer() characteristic_set = CharacteristicsSerializers(many=True) and my view, I know it's ugly but I just can figure out what I'm doing wrong here class AnimalView(APIView): def post(self, request): serializer = AnimalSerializer(data=request.data) if not serializer.is_valid(): return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) group_pop = serializer.data.pop('group') queryset = Group.objects.all() serializer_group = GroupSerializer(queryset, many=True) for group in serializer_group.data: if group_pop['name'] == group['name']: animal = Animal.objects.create(**serializer.data, group=group) else: group = Group.objects.create(**group_pop) animal = Animal.objects.create(**serializer.data, group=group_pop) characteristic_set = serializer.data.pop('characteristic_set') for characteristic in characteristic_set: Characteristic.objects.create(**characteristic, animal=animal) serializer = AnimalSerializer(animal) return … -
error auctions.models.Listing.DoesNotExist: Listing matching query does not exist. I am just starting learning django, what is wrong in my code?
Here is my views.py file: from django.contrib.auth import authenticate, login, logout from django.db import IntegrityError from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import render from django.contrib.auth.decorators import login_required from django.urls import reverse from .models import * def index(request): return render(request, "auctions/index.html" , { "listings" : Listing.objects.all() }) def login_view(request): if request.method == "POST": # Attempt to sign user in username = request.POST["username"] password = request.POST["password"] user = authenticate(request, username=username, password=password) # Check if authentication successful if user is not None: login(request, user) return HttpResponseRedirect(reverse("index")) else: return render(request, "auctions/login.html", { "message": "Invalid username and/or password." }) else: return render(request, "auctions/login.html") def logout_view(request): logout(request) return HttpResponseRedirect(reverse("index")) def register(request): if request.method == "POST": username = request.POST["username"] email = request.POST["email"] # Ensure password matches confirmation password = request.POST["password"] confirmation = request.POST["confirmation"] if password != confirmation: return render(request, "auctions/register.html", { "message": "Passwords must match." }) # Attempt to create new user try: user = User.objects.create_user(username, email, password) user.save() except IntegrityError: return render(request, "auctions/register.html", { "message": "Username already taken." }) login(request, user) return HttpResponseRedirect(reverse("index")) else: return index(request) @login_required(login_url='login') def create(request): if request.method == "POST": title = request.POST["title"] description = request.POST["description"] price = request.POST["price"] picture = request.POST["picture"] user = User.objects.get(username=request.user) try: listing = Listing(item= title,description= description,price= price,image= … -
Count number of instances which have a parameter in a list in common
I'm building an app to keep track of a school and I'm trying to figure out how many students each course has. The way my app is structured is like this: class Course(models.Model): LEVELS = ( ('A0', 'A0'), ('A1', 'A1'), ('B0', 'B0'), ('B1', 'B1'), ('C1', 'C1'), ('C2', 'C2'), ) name = models.CharField(max_length=32) level = models.CharField(max_length=2, choices=LEVELS) class Student(models.Model): name = models.CharField(max_length=32) school = models.ForeignKey(School, on_delete=models.CASCADE) course = models.ManyToManyField(Course) So, the students in the API look something like this: [ { "id": 1, "name": "Diego", "school": 2, "course": [8] }, { "id": 2, "name": "Garry", "school": 2, "course": [1] }, { "id": 3, "name": "Dr Henrick", "school": 2, "course": [8] }, ] Now the question comes in my serializer, where I'd like to get a count for each course, ideally in a dict structure that would look something like this: { 8: 2, 1: 1} What I've done consists of getting all of the students from the db and looping over their courses list, but I wonder if I could do something like that with Django's query system. -
how I can change Django Allauth email verification through OTP instead of activation link
I am working on a project I need that the Django All-Auth email verification through OTP Instead of activation link. Currently and Default Behaviour of Django all-auth to confirm email using activation link.i want to replace the Django email verification method and use OTP verification -
How to run a function with an infinite loop after rendering a page in Django
I'm writting a Django web application which will work as a tweet bot. At some point in the app the user will have to fill up a form which will decide what kind of tweets will be posted. When the user submits the form I want to render a web page to inform the user that the app is running in the background and after that I want to run the infinite loop that actually do the tweeting. My question is, how can I render a web page (from the views file) and then run the actual function (which lives in another file)? Passing the info of the form to the posting view: random_object = Random.objects.create(quotes=quotesSwitch, jokes=jokesSwitch, chuckNorris=chukNorrisSwitch, movieReview=movieReviewsSwitch, periodicityNumber=periodicityNumber, periodicity=periodicity) atributes = { 'random_object': random_object } return render(request, 'posting.html', {'random_object': atributes}) and the posting view: def posting(request): obj = Random(request.POST) random_func(obj) #This is the function with the infinite loop return render(request, 'posting.html')