Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to handle external API's JWT authentication from my Django application?
I am consuming an external RESTful API for my Django application, I want to understand how to handle JWT authentication for the API from my Django app Following is the JWT token generation code as mentioned in the documentation: 'use strict'; const path = require('path'); const fs = require('fs'); var jwt = require('jsonwebtoken'); var privateKey = fs.readFileSync("./devSandbox.key","utf8"); var payload = {}; var currentTime = Math.floor(Date.now() / 1000); var signOptions = { algorithm: "RS512" }; payload.iss = "adf50bf3-8b0f-479d-962d-4031ebadac9a"; payload.iat = currentTime; payload.exp = currentTime + 1800; payload.sub = "sbMem5c3418773ef071"; var token = jwt.sign(payload, privateKey, signOptions); console.log("Printing token: "+ token); Can someone please guide me as to how can I update my tokens from Django? Currently, I have to manually run this code and update tokens wherever required? Is there a better way to do it? Thanks. -
Django Class based and Function Based Views
everyone, I have one question. what is the difference between Class and Function-Based Views in Django and witch one is Good for Big and For low style Projects. and why I should use Function or Class-based views. thank you very much guys <3 -
Mathjax config.js not found in Docker
I am trying to run a Django project in Docker that uses MathJax inside. I listed MathJax in package.json: /* package.json */ { ... "dependencies": { ... "mathjax": "2.7.4", ... } } I included MathJax in my index.html like this: <!-- index.html --> ... <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$','$'], ['\\(','\\)']]}, jax: ["input/TeX","output/HTML-CSS"] }); </script> <script type="text/javascript" src="/static/mathjax/MathJax.js?config=TeX-AMS_CHTML"></script> Locally it works fine. I can see it additionally requests some extra files: /static/mathjax/jax/input/TeX/config.js?V=2.7.4 /static/mathjax/jax/output/HTML-CSS/config.js?V=2.7.4 /static/mathjax/extensions/MathMenu.js?V=2.7.4 /static/mathjax/extensions/MathZoom.js?V=2.7.4 When I try to run it in a docker container, I can see that it requests different files and can't find them. Instead of the files above it tries: /jax/input/TeX/config.js?V=2.7.4 /jax/output/HTML-CSS/config.js?V=2.7.4 /extensions/MathMenu.js?V=2.7.4 /extensions/MathZoom.js?V=2.7.4 That can't be correct. It looks like MathJax confuses root paths to request the necessary additional files. How can I fix it? Some details about how I run it under Docker. I configured Nginx (out of docker container): server { listen 80; server_name myproj.local; location /static { alias /path/to/collected/static; } location / { proxy_pass http://127.0.0.1:8000; } } My Dockerfile is ordinary: FROM python:3.7 ENV PYTHONUNBUFFERED 1 WORKDIR /usr/src/app RUN curl -sL https://deb.nodesource.com/setup_12.x -o nodesource_setup.sh; \ chmod 755 nodesource_setup.sh; \ ./nodesource_setup.sh; \ apt-get update; \ apt-get install -y nodejs; \ rm nodesource_setup.sh EXPOSE … -
How to add days in the current date? using script and django
I have this code in my html <div class="modal-body"> {% for me in ako %} Date: <input type="hidden" value="{{me.id}}" name="date" id="date">{{me.enddate}} <input type="hidden" value="{{me.id}}" name="id" hidden><p>{{me.Email}}</p> {% endfor %} <select> {% for perfume in s %} <option value="{{perfume.id}}" id="addDays">{{perfume.product}} - {{perfume.adddate}} Days</option> {% endfor %} </select> </div> Example if the user selected the classic perfume it will add days in the {{me.enddate}} 7days + March 8, 2020 = March 15, 2020 just like that, but i dont know how to do it in script, please help me guys <script> ?????? </script> -
How to change state of app in django from client side
I'm new to Django (in server side programation in general) and I don't know how to declare a state and be able to updated it from client side. What I want to do is be able for some users to set a "maintenance" state (boolean) to true or false. I'm using django rest_framework. Can someone give me a clue or documentation to read? Thanks -
Enum ValueError python3 when starting Django
I am trying run my django app using uwsgi, but getting these error: ValueError: names are reserved for future Enum use Command: python3 manage.py runserver 0.0.0.0:8000 Result: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/usr/local/lib/python3.5/dist-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.5/dist-packages/django/core/management/__init__.py", line 370, in execute _parser = self.fetch_command('runserver').create_parser('django', 'runserver') File "/usr/local/lib/python3.5/dist-packages/django/core/management/__init__.py", line 244, in fetch_command klass = load_command_class(app_name, subcommand) File "/usr/local/lib/python3.5/dist-packages/django/core/management/__init__.py", line 37, in load_command_class module = import_module('%s.management.commands.%s' % (app_name, name)) File "/usr/lib/python3.5/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 986, in _gcd_import File "<frozen importlib._bootstrap>", line 969, in _find_and_load File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 673, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 665, in exec_module File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed File "/usr/local/lib/python3.5/dist-packages/django/core/management/commands/runserver.py", line 10, in <module> from django.core.servers.basehttp import ( File "/usr/local/lib/python3.5/dist-packages/django/core/servers/basehttp.py", line 17, in <module> from django.core.handlers.wsgi import LimitedStream File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/wsgi.py", line 6, in <module> from django.core.handlers import base File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/base.py", line 8, in <module> from django.urls import get_resolver, set_urlconf File "/usr/local/lib/python3.5/dist-packages/django/urls/__init__.py", line 1, in <module> from .base import ( File "/usr/local/lib/python3.5/dist-packages/django/urls/base.py", line 9, in <module> from .exceptions import NoReverseMatch, Resolver404 File … -
Django FileNotFoundError at /register/
** All the dependencies are installed. While my images are being served and are viewable in my app, when I attempt to login or register the, I get the error. It's only when using the form and not selecting an image does it not work properly.I've look around for a while but have yet to come up with anything that could help. Any ideas? Any help is much appreciated. traceback below.** C:\Users\merto\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\exception.py in inner response = get_response(request) … ▶ Local vars C:\Users\merto\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py in _get_response response = self.process_exception_by_middleware(e, request) … ▶ Local vars C:\Users\merto\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) … ▶ Local vars C:\Users\merto\PycharmProjects\sample\users\views.py in register form.save() … ▶ Local vars C:\Users\merto\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\contrib\auth\forms.py in save user.save() … ▶ Local vars C:\Users\merto\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\contrib\auth\base_user.py in save super().save(*args, **kwargs) … ▶ Local vars C:\Users\merto\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\base.py in save self.save_base(using=using, force_insert=force_insert, … ▶ Local vars C:\Users\merto\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\base.py in save_base post_save.send( … ▶ Local vars C:\Users\merto\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\dispatch\dispatcher.py in send return [ … ▶ Local vars C:\Users\merto\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\dispatch\dispatcher.py in <listcomp> (receiver, receiver(signal=self, sender=sender, **named)) … ▶ Local vars C:\Users\merto\PycharmProjects\sample\users\signals.py in create_profile Profile.objects.create(user=instance) … ▶ Local vars C:\Users\merto\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\manager.py in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) … ▶ Local vars C:\Users\merto\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\query.py in create obj.save(force_insert=True, using=self.db) … ▶ Local vars C:\Users\merto\PycharmProjects\sample\users\models.py in save img = Image.open(storage.open(self.image.path)) … -
Django / Postgresql project + multiple databases architecture advice
I've got a pet Django / Postgresql project with multiple apps. It's not yet deployed. It's industry specific. It's target audience is worldwide. It's likely to have translated versions for certain countries later. It's not expected that its traffic will ever match that of the most popular websites. It's, however, expected that traffic may grow to millions of requests per day. It's expected that DB reads will prevail but writes will still be often. It's primary content will be text and files (usually up to 1 megabyte), no video or audio. Should I now bother about scaling, multiple databases, and the like? I guess the answer is no but still not sure. The following options are considered (but not limited to). Don't bother now. Add more resources later if needed. Even with millions of requests per day one DB would be enough. Don't bother now. Add replicas later if needed. Don't bother now. Partition by tables or rows later if needed. Partition now by grouping apps into separate databases on the same node. If later traffic happens to be high, put the databases on separate nodes. So what would you advice. -
CORS enable in Django Rest Framework
I am new in API backend development. I know its an old question. But I really could not figure out what wrong with my approach in order to achieve CORS enabled. I tried with quickstart app in DRF https://www.django-rest-framework.org/tutorial/quickstart/ and followed the steps from https://pypi.org/project/django-cors-headers/. And I am still getting the exact same response header in postman. I was expecting something Access-Control-Allow-Origin in the response -
Django: HTML page Update after adding to the Database using Bootstrap modal and Json gives wrong data
I am developing a todo list app in Django, but i seem to be getting a logic error (it dosen't print out any error, but its not working right). I have a view, TaskListView. I added extra context by overriding the get_context_data method. So on the page, I have three objects: Category, CustomUser and Task. When the page loads, it gets the Categories that were created by that specific user and those created by the admin. I have a bootstrap modal, using Json to add new Categories to the database, and to update the list. When it loads first, it works fine (the Categories display correctly). But after I add a Category to the database, instead of it to update the Category list with the newly added Category, it displays the Categories created by admin twice. I am using a view, category_create, for the modal to add a new Category urls.py: from django.urls import path, re_path from django.conf.urls import url, include from .views import TaskListView, task_create, category_create urlpatterns = [ path('', TaskListView.as_view(), name='task_list'), re_path(r'^create/$', views.task_create, name='task_create'), re_path(r'^category/create/$', views.category_create, name='category_create'), ] models.py: class Category(models.Model): category_name = models.CharField(max_length=50) user = models.ForeignKey(CustomUser, null = True, on_delete=models.CASCADE) def __str__(self): return '%s ' % (self.category_name) … -
Vue array to django
Im having a lot of issues on this and couldn't find a solution, im using Django and vue.js I have created a form which allows me to add multiple inputs on a certain click, this part works fine. However what I want to do on submit is add these inputs in my django view to my models. My model set up is a one to one for my title and then a one to many for my paragraph and my header. My hope was to simply loop through all my inputs check what 'type'(title, para or header) it is and then assign to the correct model. Any help or guidance on how to do this is much appreciated, below is the code I have so far HTML {% extends 'blog/base.html' %} {% block content %} {% load static %} <form method="post"> {% csrf_token %} <div class="con"> <button type="button" name="button" @click='addHead()'> header </button> <button type="button" name="button" @click='addPara()'> Para </button> <div id="body-fields"> <div class="car-body" v-for="(post, index) in posts"> {% verbatim %} <input style='display:none'name = 'count' v-bind:value='[index]' > {% endverbatim %} <input type="textbox" v-bind:name='[post.type]' v-model='post.content'> <span style="float:right;background-color:green" @click='removeForm(index)'> x </span> </div> </div> <input type="submit" vaule="save"/> </div> </form> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> <script src="{% static 'blog/JS/main.js'%}" … -
Getting TemplateDoesNotExist at /
Im getting error TemplateDoesNotExist at /AI.html I tried to look for the problem but i cant find it. Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 3.0.4 Exception Type: TemplateDoesNotExist Exception Value: AI.html Exception Location: C:\Users\Davids dator\AppData\Local\Programs\Python\Python37\lib\site-packages\django\template\loader.py in get_template, line 19 Python Executable: C:\Users\Davids dator\AppData\Local\Programs\Python\Python37\python.exe Python Version: 3.7.6 Python Path: ['C:\Users\Davids dator\Desktop\templateee\Mysite', 'C:\Users\Davids ' 'dator\AppData\Local\Programs\Python\Python37\python37.zip', 'C:\Users\Davids dator\AppData\Local\Programs\Python\Python37\DLLs', 'C:\Users\Davids dator\AppData\Local\Programs\Python\Python37\lib', 'C:\Users\Davids dator\AppData\Local\Programs\Python\Python37', 'C:\Users\Davids dator\AppData\Roaming\Python\Python37\site-packages', 'C:\Users\Davids ' 'dator\AppData\Local\Programs\Python\Python37\lib\site-packages'] Traceback Environment: Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 3.0.4 Python Version: 3.7.6 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'MyApp'] Installed 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'] Template loader postmortem Django tried loading these templates, in this order: Using engine django: * django.template.loaders.app_directories.Loader: C:\Users\Davids dator\AppData\Local\Programs\Python\Python37\lib\site-packages\django\contrib\admin\templates\AI.html (Source does not exist) * django.template.loaders.app_directories.Loader: C:\Users\Davids dator\AppData\Local\Programs\Python\Python37\lib\site-packages\django\contrib\auth\templates\AI.html (Source does not exist) Traceback (most recent call last): File "C:\Users\Davids dator\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\Davids dator\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\Davids dator\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Davids dator\Desktop\templateee\Mysite\MyApp\views.py", line 36, in Index return render(request, "AI.html", {'form': context}) File "C:\Users\Davids dator\AppData\Local\Programs\Python\Python37\lib\site-packages\django\shortcuts.py", line 19, in render content = loader.render_to_string(template_name, context, request, using=using) File "C:\Users\Davids dator\AppData\Local\Programs\Python\Python37\lib\site-packages\django\template\loader.py", line 61, in render_to_string template = … -
display name of month based on number in python django month number store in database like 1,2,3......12
{{ dt.month }} Had try this but work only when we have full date {{ dt.add_date|date:"F" }} //get date from db like "2020-03-0718:17:02.300948+05:30" this is working {{ dt.month|date:"M" }} //get only number from db like 03 this is not work -
How to resolve Django Error in formatting: AttributeError: 'Habit' object has no attribute 'goal'
I runserver to test my Habit Tracker app. Not sure why I get Error in formatting: AttributeError: 'Habit' object has no attribute 'goal'. Have included my models.py. I need your help understanding what I have written incorrectly and how to fix the code. thank you. class Habit(models.Model): name = models.CharField(max_length=60) goal_nbr = models.IntegerField(default=0, null=True, blank=True) goal_description = models.CharField(max_length=60, null=True, blank=True) start_date = models.DateField() end_date = models.DateField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) user = models.ForeignKey( User, related_name="habit", on_delete=models.CASCADE) @property def duration(self): delta = end_date - start_date return f'{ delta } days' def __str__(self): return f"Your chosen habit is {self.name}, with a goal of {self.goal_nbr} {self.goal._description} for {self.duration} days, from {self.start_date} to {self.end_date}" class Activity(models.Model): # name = models.CharField(max_length=60) result_nbr = models.IntegerField(default=0, null=True, blank=True) created_at = models.DateField(auto_now_add=True) updated_at = models.DateField(auto_now=True) user = models.ForeignKey( User, related_name="activity", on_delete=models.CASCADE) habit = models.ForeignKey( 'Habit', related_name="activity", on_delete=models.CASCADE) @property def diff_between_goal_result(self): diff_nbr = result_nbr - self.habit.goal_nbr return f'{ diff_nbr }' class Meta: constraints = [models.UniqueConstraint( fields=['created_at', 'habit'], name='one_update_per_day'), ] def __str__(self): return f"Today you achieved: {self.result_nbr} of your {self.habit.name} {self.habit.goal_description}" -
How to uninstall python 2.17.13, and keep python 3.7.6 as the default on debian 9
I installed a Django package on GCP (Debian 9 OS), that comes with the following softwares: Django (2.2.9) Git (2.25.0) Apache (2.4.41) lego (3.3.0) MySQL (5.7.29) Node.js (10.18.1) OpenSSL (1.1.1d) PostgreSQL (11.6) Python (3.7.6) SQLite (3.31.0.) Subversion (1.13.0) When I type the command python -V I get the following python version: 2.17.13 When I type python3 -V I get the following version: 3.7.6 How can I uninstall the previous version permanently and keep the current one as the default? -
django.utils.datastructures.MultiValueDictKeyError: 'password'
I'm using Django3 and py3 i'm trying to create registration and login pages by using django forms. my registrations part was succeeded i can put data in database table. but when it comes to login part im getting this error can some one please help me This is my view file: from django.http import HttpResponse from django.shortcuts import render, redirect from django.contrib.auth.models import auth from firstapp.models import Customers # Create your views here. def home(request): return render(request, 'home.html') def register(request): return render(request, 'register.html') def reg_success(request): name = request.POST['name'] username = request.POST['username'] password = request.POST['password'] email = request.POST['email'] mobile = request.POST['mobile'] # return HttpResponse("<h2>UserRegistered Successfully</h2>") if request.method == 'POST': user = Customers.objects.create(name=name, username=username, password=password, email=email, mobile=mobile) user.save() print("User Created") return render(request, 'reg_success.html', {'username': username}) else: return render(request, 'register.html') def login(request): return render(request, 'login.html') def log_success(request): username = request.POST['username'] password = request.POST['password'] if request.method == 'POST': user = auth.authenticate(username=username, password=password) if user is not None: auth.login(request, user) return render(request, 'log_success.html', {'username': username}) else: return HttpResponse("Invalid Details Given") #return redirect(login) else: return redirect(login) This is my html file for log_success.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Login Success</title> </head> <body> <form method="post"> {% csrf_token %} <h2 style="color:green">Welcome {{username}}</h2> <p>Here is Your Bio … -
normalization in django model between course and course location
i want to normalize my django model which includes Institutes and Location ,this model structure is right ? class Institute(models.Model): institute_name = models.OneToOneField(CustomUser,on_delete=models.CASCADE) institute_id = models.SlugField(unique=True,default=slug_generator()) institute_name.is_institute = True institute_logo = models.ImageField(upload_to='profiles',default='profile.png') city_name = models.CharField(choices=city_choices,default=erbil,max_length=40) specific_location = CharField(choices=locations,default='') or something like that : class Institute(models.Model): institute_name = models.OneToOneField(CustomUser,on_delete=models.CASCADE) institute_id = models.SlugField(unique=True,default=slug_generator()) institute_location = models.ForeignKey(Location) institute_name.is_institute = True institute_logo = models.ImageField(upload_to='profiles',default='profile.png') class Location(models.Model): city_name = models.CharField(choices=city_choices,default=erbil,max_length=40) specific_location = CharField(choices=locations,default='') def __str__(self): return self.city_choices thanks for advice -
'unique_together' refers to the nonexistent field 'slug'
in category class I'm using a function for slug to accept Arabic letters but after adding this function and using it I get that error. models.py: class Category(models.Model): name = models.CharField(max_length=200) parent = models.ForeignKey( 'self', blank=True, null=True, related_name='children', on_delete=models.CASCADE) def __str__(self): full_path = [self.name] k = self.parent while k is not None: full_path.append(k.name) k = k.parent return ' -> '.join(full_path[::-1]) def save(self, *args, **kwargs): super().save(*args, **kwargs) self.slug = slugify(self.title) class Meta: unique_together = ('slug', 'parent',) verbose_name_plural = "categories" and this is the slugify function: def slugify(str): str = str.replace(" ", "-") str = str.replace(",", "-") str = str.replace("(", "-") str = str.replace(")", "") str = str.replace("؟", "") return str before this I was using slugField but that didn't work for arabic. If there is another way for that without using self made function please tell me. and also I've included this at top: # -*- coding: utf-8 -*- -
Django REST: TypeError: Object of type 'Language' is not JSON serializable
When I tried to add value of language python3 returns error that this object is not JSON serializible. models: from django.db import models from django.contrib.auth.models import AbstractUser, AbstractBaseUser class Admin(AbstractUser): class Meta(AbstractUser.Meta): pass class HahaUser(AbstractBaseUser): is_admin = models.BooleanField(default=False, verbose_name='is administrator?') born = models.PositiveSmallIntegerField(verbose_name='born year') rating = models.PositiveIntegerField(default=0, verbose_name='user rating') email = models.EmailField(verbose_name='email') nickname = models.CharField(max_length=32, verbose_name='useraname') password = models.CharField(max_length=100, verbose_name='password') # on forms add widget=forms.PasswordInput language = models.ForeignKey('Language', on_delete=models.PROTECT) country = models.ForeignKey('Country', on_delete=models.PROTECT) def __str__(self): return self.nickname class Meta: verbose_name = 'User' verbose_name_plural = 'Users' ordering = ['nickname'] class Language(models.Model): name = models.CharField(max_length=20, verbose_name='language name') def __str__(self): return self.name class Meta: verbose_name = 'Language' verbose_name_plural = 'Languages' class Country(models.Model): name_ua = models.CharField(max_length=20, verbose_name='country name in Ukranian') name_en = models.CharField(max_length=20, verbose_name='country name in English') name_ru = models.CharField(max_length=20, verbose_name='country name in Russian') def __str__(self): return self.name_en class Meta: verbose_name = 'Country' verbose_name_plural = 'Countries' Serializers: from rest_framework import serializers from main import models class RegistrationSerializer(serializers.ModelSerializer): password2 = serializers.CharField(style={'input_type': 'password'}, write_only=True, required=True) class Meta: model = models.HahaUser fields = ['nickname', 'password', 'password2', 'language', 'country', 'email', 'born'] extra_kwargs = { 'password': {'write_only': True} } def save(self): account = models.HahaUser.objects.create( email=self.validated_data['email'], nickname=self.validated_data['nickname'], language=self.validated_data['language'], born=self.validated_data['born'], country=self.validated_data['country'] ) password = self.validated_data['password'] password2 = self.validated_data['password2'] if password != … -
How to create table from views and display it to HTML?
How do I create a table using this query that corresponds to each other? I'm completely stuck with this problem, I tried to solve it for several days. views.py corevalues = CoreValues.objects.all().order_by('Display_Sequence') marking = StudentBehaviorMarking.objects.all() corevaluesdescription = CoreValuesDescription.objects.values('id', 'Description').distinct( 'Description').order_by('Description') period = gradingPeriod.objects.filter(id=coreperiod).order_by('Display_Sequence') studentcorevalues = StudentsCoreValuesDescription.objects.filter(Teacher=teacher).filter( GradeLevel=gradelevel.values_list('Description')) \ .values('Students_Enrollment_Records').distinct('Students_Enrollment_Records').order_by( 'Students_Enrollment_Records') student = StudentPeriodSummary.objects.filter(Teacher=teacher).filter( GradeLevel__in=gradelevel.values_list('id')) The results I want to achieve: My models class CoreValues(models.Model): Description = models.CharField(max_length=500, null=True, blank=True) Display_Sequence = models.IntegerField(null=True, blank=True) . class CoreValuesDescription(models.Model): Core_Values = models.ForeignKey(CoreValues,on_delete=models.CASCADE, null=True) Description = models.TextField(max_length=500, null=True, blank=True) grading_Period = models.ForeignKey(gradingPeriod, on_delete=models.CASCADE) Display_Sequence = models.IntegerField(null=True, blank=True) class StudentBehaviorMarking(models.Model): Marking = models.CharField(max_length=500, null=True, blank=True) Non_numerical_Rating = models.CharField(max_length=500, null=True, blank=True) class StudentPeriodSummary(models.Model): Teacher = models.ForeignKey(EmployeeUser, on_delete=models.CASCADE,null=True, blank=True) Students_Enrollment_Records = models.ForeignKey(StudentSubjectGrade,on_delete=models.CASCADE) It is possible to create a table using Python, right? UPDATE When I try this to my views.py: students = StudentsCoreValuesDescription.objects.filter(grading_Period=coreperiod) \ .values('id', 'Marking', 'Students_Enrollment_Records__Students_Enrollment_Records__Students_Enrollment_Records__Students_Enrollment_Records__Student_Users__Firstname', 'Students_Enrollment_Records__Students_Enrollment_Records__Students_Enrollment_Records__Students_Enrollment_Records__Student_Users__Lastname') \ .distinct( 'Students_Enrollment_Records__Students_Enrollment_Records__Students_Enrollment_Records__Students_Enrollment_Records__Student_Users__Firstname', 'Students_Enrollment_Records__Students_Enrollment_Records__Students_Enrollment_Records__Students_Enrollment_Records__Student_Users__Lastname') \ .order_by( 'Students_Enrollment_Records__Students_Enrollment_Records__Students_Enrollment_Records__Students_Enrollment_Records__Student_Users__Lastname', 'Students_Enrollment_Records__Students_Enrollment_Records__Students_Enrollment_Records__Students_Enrollment_Records__Student_Users__Firstname') gradelevel = EducationLevel.objects.filter(id__in=coregradelevel).distinct().order_by('id') markings = StudentBehaviorMarking.objects.all() corevaluesperiod = CoreValuesDescription.objects.filter(grading_Period=coreperiod).order_by('Display_Sequence') table = [] student_name = None table_row = None columns = len(corevaluesperiod) + 1 table_header = ['Core Values'] table_header.extend(corevaluesperiod) table.append(table_header) for student in students: if not student[ 'Students_Enrollment_Records__Students_Enrollment_Records__Students_Enrollment_Records__Students_Enrollment_Records__Student_Users__Firstname'] + ' ' + \ student[ 'Students_Enrollment_Records__Students_Enrollment_Records__Students_Enrollment_Records__Students_Enrollment_Records__Student_Users__Lastname'] == student_name: if not table_row is None: … -
External API's JWT generation from Django application
I am consuming an external RESTful API for my Django application, I want to achieve the following things Generate a JWT Open home page to do some registration (using another API) Again generate a JWT Make API calls The code to generate JWT is in node js. I just want some directions as to how this is done automatically. currently, I manually run the code to get the JWT and copy-paste it wherever it is required. I tried to run the token generation code from views.py using different libraries but no luck. Can someone please guide me on how this is done? Thanks -
How to render form with class-based view?
I have an index page: views.py class IndexView(TemplateView): template_name = "index.html" urls.py urlpatterns = [ path('', IndexView.as_view()), ] And I need to render form in this page index.html {% block content %} <!-- Other blocks --> <div id="input"> <form method="POST" class="text-form"> {% csrf_token %} {{ form.as_p }} <button type="submit" class="submit btn">Submit</button> </form> </div> <!-- Other blocks --> {% endblock %} forms.py class TextForm(forms.Form): text = forms.CharField(widget=forms.Textarea) There is a topic about class-based views forms handling but it is not clear for me how to render HTML with this form -
Django pivot table without id and primary key
On the database i have 3 tables: languages cities city_language city_language Table: +-------------+---------------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +-------------+---------------------+------+-----+---------+-------+ | city_id | bigint(20) unsigned | NO | PRI | NULL | | | language_id | bigint(20) unsigned | NO | PRI | NULL | | | name | varchar(255) | NO | | NULL | | +-------------+---------------------+------+-----+---------+-------+ Model class CityLanguage(models.Model): city = models.ForeignKey('Cities', models.DO_NOTHING) language = models.ForeignKey('Languages', models.DO_NOTHING) name = models.CharField(max_length=255) class Meta: managed = False db_table = 'city_language' unique_together = (('city', 'language'),) Model doesn't have id field and primary key also my table doesn't have id column. If i run this code i got error: (1054, "Unknown column 'city_language.id' in 'field list'") If i define primary key for a column this column values should unique. If i use primary_key when i want to put same city with different languages i get With this city (name or language it depends on which column choose for primary key) already exists. I don't want to create id column for pivot table. There is no reason create id column for pivot table. Please can you tell me how can i use pivot table with correct … -
How to add Widgets to UpdateView in Django
I need to add this widget to the django UpdateView, class tlistUpdate(LoginRequiredMixin,UpdateView): fields = ('title', 'thumbnail', 'content', 'tags') model = htmlpage template_name = 'blog/create_form.html' Tried adding widgets = { 'content': SummernoteWidget(), } and content = forms.CharField(widget=SummernoteWidget()) But it did't work. -
How to create api for Implement Dependent/Chained Dropdown List?
How to Implement Dependent/Chained Dropdown List with django rest framework?