Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Custom HTML renderer returning empty page
I have this custom HTML renderer using Django Rest Framework: from rest_framework.renderers import TemplateHTMLRenderer class CustomHTMLRenderer(TemplateHTMLRenderer): def renderer_context = renderer_context or {} view = renderer_context['view'] request = renderer_context['request'] response = renderer_context['response'] if response.exception: template = self.get_exception_template(response) else: template_names = self.get_template_names(response, view) template = self.resolve_template(template_names) context = self.get_template_context({'content': data}, renderer_context) return template.render(context) And this is my view for a search carried out on my Solr server: import os from django.conf import settings from rest_framework.generics import GenericAPIView from rest_framework.response import Response from rest_framework.renderers import JSONRenderer from rest_framework.pagination import LimitOffsetPagination import collections from collections import OrderedDict from rest_framework.settings import api_settings import scorched from scorched.strings import DismaxString from bassculture.renderers.custom_html_renderer import CustomHTMLRenderer class SearchResultsPagination(LimitOffsetPagination): def get_paginated_response(self, data): self.solr_response = data['solr_response'] self.offset = self.solr_response.result.start self.limit = len(data['records']) self.count = self.solr_response.result.numFound self.request = data['request'] resp = Response(OrderedDict([ ('count', self.count), ('next', self.get_next_link()), ('previous', self.get_previous_link()), ('results', data['records']), ('facets', self.solr_response.facet_counts.facet_fields), ('params', self.solr_response.params), ('highlighting', self.solr_response.highlighting), ('limit', self.limit), ])) return resp class SearchViewHTMLRenderer(CustomHTMLRenderer): template_name = "search/search.html" class SearchView(GenericAPIView): renderer_classes = [JSONRenderer, SearchViewHTMLRenderer] pagination_class = SearchResultsPagination def get(self, request, *args, **kwargs): querydict = request.GET offset = querydict.get('offset', 0) fcq = {} for f in settings.SEARCH_FACETS: if querydict.get(f, None): fcq[f] = querydict.get(f) fq = {} if querydict.get('fq'): fq = querydict.get('fq') else: fq = '*' … -
Django loops infinitly after startapp method call
I'm doing the CS50Web course, and there is a Django project in which I want to create a new app called "wikipedia". The problem is that after I run this command in Windows PowerShell: python manage.py runserver this loop happens: loop print I don't know what I did wrong for that to happen. After running python manage.py startapp wikipedia , I: went to my Django project and added 'wikipedia' in the installeds apps in settings.py went to urls.py and added a path like this: path("wiki/", include("wikipedia.urls)) And then I tried running the server. What did I do wrong? -
How can I get pdf2image working on Heroku?
I have added multiple buildpacks: https://buildpack-registry.s3.amazonaws.com/buildpacks/heroku-community/apt.tgz https://github.com/survantjames/heroku-buildpack-poppler.git https://github.com/amitree/heroku-buildpack-poppler I even tried the xpdfrc buildpack but I still can't get it to work. This is the error: pdfinfo: error while loading shared libraries: libpng12.so.0: cannot open shared object file: No such file or directory -
How to make multiple updates with different values
Please, how do i create a form that returns a list for all name attributes in the form. I have a form that has multiple of the same inputs. How do i make it POST data so that in my views i can do something like... name = request.POST.getlist('name') I need this help. -
Query with annotated aggregation over the same model
I have the following models: class P(models.Model): name = models.CharField(max_length=30, blank=False) class pr(models.Model): p = models.ForeignKey(P, on_delete=models.CASCADE, related_name='cs') r = models.CharField(max_length=1) c = models.ForeignKey(P, on_delete=models.CASCADE, related_name='ps') rc = models.PositiveSmallIntegerField() class Meta: unique_together = (('p', 'c'),) and the data: "id","name" 69,"Hunter" 104,"Savannah" 198,"Adrian" 205,"Andrew" 213,"Matthew" 214,"Aiden" 218,"Madison" 219,"Harper" --- "id","r","rc","c_id","p_id" 7556,"F",1,219,213 7557,"M",1,219,218 7559,"H",3,218,213 7572,"F",1,214,213 7573,"M",1,214,218 7604,"F",1,198,213 7605,"M",1,198,218 7788,"H",3,104,205 7789,"F",1,104,213 7790,"M",1,104,218 7866,"M",1,69,104 7867,"F",1,69,205 For a pr model instance I need to find in how many rows the associated p_id exists. These queries generate the intended result: ro = pr.objects.get(pk=7604) cntp = pr.objects.filter(Q(p = ro.p) | Q(c = ro.p)).count() The above queries will hit the database 2 times, I want to hit the database one time so I wrote this query: ro = pr.objects.filter(pk=7604).annotate(cntp=Subquery(pr.objects.filter(Q(p = OuterRef('p')) | Q(c = OuterRef('parent'))).count())) That query generates error "This queryset contains a reference to an outer query and may only be used in a subquery." so used the method mentioned in Simple Subquery with OuterRef: ro = pr.objects.filter(pk=7604).annotate(cntp=Subquery(pr.objects.filter(Q(p = OuterRef('p')) | Q(c = OuterRef('c'))).annotate(count=Count('pk')))) Again this query generates another error "subquery must return only one column"! Can Django ORM be used to generate the intended results? Environment:Django Version: 3.0.4 Python version: 3.7.3 Database:PostgreSQL 11.9 (Debian 11.9-0+deb10u1) on … -
How could I ,,split'' a set of values from html button?
Let's suppose i'm sending a set of values in html (with value="{{ q }}") and i want to open this set in django view and then save them into another model? How could I do this? (those commented out lines are what I thought would work) <form action="." method="post"> {% for q in questions_data %} <ul> <li>{{ q.question }}</li> </ul> {% csrf_token %} <button type="submit" name="answerButton" value="{{ q }}">{{ q.answer1 }}</button> <button type="submit" name="answerButton" value="{{ q }}">{{ q.answer2 }}</button> {% endfor %} </form> views if request.method == 'POST': #question_id = interest = request.POST.get('answerButton') answered = UserInterest() #answered.selectedInterest = interest['selectedInterest'] #answered.q_id = interest['q_id'] answered.save() return render(request, 'account/dashboard.html', {'section': 'dashboard'}) -
How to retrieve index number from a 'for' loop of a dict in Django Views
I am trying to get the index number of {% for p in mydict_1 %} so that I can use that index on another dict to get the value. How to do this within Django Views? Data from both dicts corresponds to the index in a series. mydict_1 = [{'itemCode': 'AZ001', 'price': 15.52}, {'itemCode': 'AB01', 'price': 31.2}, {'itemCode': 'AP01', 'price': 1.2}] #list of dict mydict_2 = [{'prop': 'val000'}, {'prop': 'val008'}, {'prop': 'val009'}] #list of dict {% for p in mydict_1 %} <tr> <td><a>{{p.itemCode}}</a></td> <td><a>{{p.price}}</a></td> #Want to use p's index number to get value of that index from mydict_2 <td><a>{{mydict_2.[p].prop}}</a></td> #How to do this correctly? Expecting val000 for index 0 </tr> {% endfor %} -
DJANGO make JSON Object from difeerent model
I want make JSON Object from diferent model, How to do it? ktg_chart = Kategori.objects.all() ip = Ktg_Mhs_Ip.objects.filter(nim=nim) chart_ktg = [] for i, ktg in ktg_chart: jsktg = { 'kategori' : ktg[i][2], 'ip' : ip[0][i] } chart_ktg.append(jsktg) dktg = json.dumps(chart_ktg) And result of the query is this : ktg_chart = Kategori.objects.all() ip = Ktg_Mhs_Ip.objects.filter(nim=nim) -
How to run a django server in debug mode in Pycharm using Makefile?
I'm working on a django project where we have a Makefile that's used to run server. Basically we have a section run with command to run django server in it python manage.py runserver. How do I run this make run in debugging mode in Pycharm. Generally if it is just a normal django server, we would setup a run configuration with python manage.py runserver and run it in debug mode and set breakpoints and do step over or step in etc. But as this is Makefile, not sure how to do this. Someone please help me with this. -
How do I implement mobile number authentication for a React Native app (Expo) with Django backend and Mongodb?
I'm currently building a mobile app using react native (expo), with a django backend and mongodb. I want the sign up + authentication to only be done with a mobile number (something like Whatsapp and Telegram), and not the standard username and password. I'm thinking about using Firebase for authentication, while still storing data in mongodb. However I read that Firebase doesn't really play well with Django. Is there a better way to do this? Any documentation will definitely help. Thanks! -
django-autocomplete-light ModelSelect2Multiple not showing up
My autocomplete field shows and works perfectly on the admin page, but when trying to generate it out of the admin, it shows as a thin vertical line. How can I fix this issue? forms.py def student_form(request): if request.method == 'POST': form = StudentForm(request.POST) if form.is_valid(): form.save() return redirect('student_form') else: form_class = StudentForm return render(request, 'form.html', {'form': form_class}) class CourseAutocomplete(autocomplete.Select2QuerySetView): def get_queryset(self): qs = CourseInstance.objects.all() if self.q: qs = qs.filter(course_name__istartswith=self.q) return qs views.py class StudentForm(autocomplete.FutureModelForm): first_name = forms.CharField(label= 'First Name ', widget=forms.TextInput) last_name = forms.CharField(label = 'Last Name ', widget=forms.TextInput) uni = forms.CharField(label = 'UNI ', widget=forms.TextInput) email = forms.CharField(label = 'Email ', widget=forms.TextInput) phone = forms.CharField(label = 'Phone number (optional)') time_zone = forms.ChoiceField( choices = TIME_ZONE_CHOICES, label = 'Time zone ') time_management = forms.ChoiceField( choices = TIME_MANAGEMENT_CHOICES, initial = 0, widget = forms.RadioSelect(attrs={'display': 'inline-block',}), label = 'How do you manage your time for assignments?') collaborative = forms.ChoiceField( choices = COLLABORATIVE_CHOICES, widget = forms.RadioSelect, label = 'How collaborative are you?') academic_seriousness = forms.ChoiceField( choices = SERIOUSNESS_CHOICES, widget = forms.RadioSelect, label = 'How serious of a student are you?') extroverted = forms.ChoiceField( choices = EXTROVERTED_CHOICES, widget = forms.RadioSelect, label = 'How extroverted are you?') discovery = forms.MultipleChoiceField(choices = DISCOVERY_CHOICES, widget = … -
Django React.JS - data displayed in web not on mobile phone after npm start and python runserver
I'm working on a Django React Web App that is compatible with both desktop and mobile web (not apps). Everything works perfectly on web, but I can't see the database contents when I view the app on the mobile browser. I can only see the front-end design. After running npm start (React) and python manage.py runserver (0.0.0.0:8000 OR ip4 address:8000 OR other hostnames) (python), I can see the interface with the data rendering on web no problem. However, after I have typed IP4_address:3000 on my mobile web browser, I can only see the frontend but not the database contents that should be displayed. I've added "localhost", "IP4-address" and "127.0.0.1" in my Django project settings. I tried adding "start": "http-server -a (localhost OR ip4 address) -p 8000". Appreciate for the help! -
Django annotate output field dict using other columns
I've got this unioning of query sets. For one of the query sets, I'm using annotations to output a dictionary like this: from django.db import models ( Table.objects .annotate(blah=Value({"id": F("parent_id", "name": F("parent__name"))}, output_field=models.JSONField(blank=True, null=True))) .values("blah") ) in which the FK parent is nullable. But I get the following error: Object of type F is not JSON serializable, which makes sense but I have no idea how else to do this. -
Creating a dropdown menu on a form using ListView that is based on elements of the object
I am using ListView and each Object has an identical form. The options for one of the elements of the form (it's a CharField) need to be one of two attributes (a choice between Object.attr1 and Object.attr2) of the corresponding object. How can I do this? class OrderForm(forms.ModelForm): class Meta: model = Order fields = ['order_type', 'price', 'location'] -
Python, Django: getting full path from file
Good evening, I'm trying to select a file ("example.csv") via a input inside my template: main.html ... <form method="post" enctype="multipart/form-data"> {% csrf_token %} <input type="file" name="myFile"> <button class="btn btn-success" type="submit">Choose</button> </form> ... After selecting and hitting the button I want to achieve the full path plus the name of the file itself as a string! views.py ... if request.method == 'POST' and request.FILES['myFile']: myFile = request.FILES['myFile'] file_path = # getting the full file path ... For example: data_name = 'example.csv' file_path = 'C:\Users\John Doe\Files' So the string should look something like this: 'C:\Users\John Doe\Files\example.csv' I tried it with os.path, but this doesn't seem to work or I'm doing something wrong here!? Thanks for all your help! -
My development server report this error after running it
My django project reports an error after running the development server: I get this error each time I run the development server: Virtual environment was activated before running the server. How do I resolve it and get my project working again? Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "c:\users\bello\anaconda3\lib\threading.py", line 916, in _bootstrap_inner self.run() File "c:\users\bello\anaconda3\lib\threading.py", line 864, in run self._target(*self._args, **self._kwargs) File "C:\Users\bello\Envs\mosque-around-you\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\bello\Envs\mosque-around-you\lib\site-packages\django\core\management\commands\runserver.py", line 110, in inner_run autoreload.raise_last_exception() File "C:\Users\bello\Envs\mosque-around-you\lib\site-packages\django\utils\autoreload.py", line 76, in raise_last_exception raise _exception[1] File "C:\Users\bello\Envs\mosque-around-you\lib\site-packages\django\core\management\__init__.py", line 357, in execute autoreload.check_errors(django.setup)() File "C:\Users\bello\Envs\mosque-around-you\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\bello\Envs\mosque-around-you\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\bello\Envs\mosque-around-you\lib\site-packages\django\apps\registry.py", line 114, in populate app_config.import_models() File "C:\Users\bello\Envs\mosque-around-you\lib\site-packages\django\apps\config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "c:\users\bello\anaconda3\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\Users\bello\Desktop\DESKTOP\EDX\mosque-around-you\mosque-around-you\mosquesinlocation\models.py", line 3, in <module> from cities_light.models import City, Region as State, Country File "C:\Users\bello\Envs\mosque-around-you\lib\site-packages\cities_light\models.py", … -
how to store requested value of a form into another form django
I have two forms, one for the teacher and the other for student_answer. In my view, I am looking for a way to store the selected value of the teacher in teacher_form, into choice.teacher which gives the following error message. Exception Value: Cannot assign " < TeacherForm bound=True, valid=Unknown, fields=(name) >": "Student_Answer.teacher" must be a "Teacher" instance. def index(request): question1 = Question.objects.get(id=1) question2 = Question.objects.get(id=2) if request.method == "POST": teacher_form = TeacherForm(request.POST) form = AnswerForm(request.POST, prefix='question1') form1 = AnswerForm(request.POST, prefix='question2') if (form.is_valid and form1.is_valid()): choice = form.save(commit=False) choice.question = question1 choice.teacher = teacher_form choice.save() choice = form1.save(commit=False) choice.question = question2 choice.teacher = teacher_form choice.save() return HttpResponseRedirect('/submit/') else: teacher_form = TeacherForm() form = AnswerForm(prefix='question1') form1 = AnswerForm(prefix='question2') context = { 'teacher_form': teacher_form, 'form': form, 'form1': form1, } return render(request, 'index.html', context) **models.py** class Question(models.Model): question = models.CharField(max_length=200) def __str__(self): return self.question class Teacher(models.Model): name = models.CharField(max_length=200) def __str__(self): return self.name class Student_Answer(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) teacher = models.ForeignKey(Teacher, on_delete=models.CASCADE) answer = models.SmallIntegerField(choices=RATING_CHOICES, default=1) -
Error when creating a foreignkey in views.py in Django
I get the following error: ValueError at /answer_question/ Cannot assign "'USERNAME_OF_MY_ACCOUNT_IN_DJANGO'": "Answer.author" must be a "Customer" instance. when I make a new object in the database in Django. views.py def answer_question(request): if request.user.is_authenticated: path = request.GET.get('path') print(str(path)) title = request.POST.get('answer-title-input') print(str(title)) context = request.POST.get('answer-context-input') print(str(context)) path=str(path) post=str(path[7:]) print("POST = " + post) post = get_object_or_404(Post, title=post) print("POST FROM DATABASE = " + str(post)) Answer.objects.create( title = title, context = context, date=("Date"), author = request.user.username, post = post, ) return redirect(path) The author should be the person who posted the answer. models.py class Customer(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank = True) name = models.CharField(max_length=200, null=True) email = models.EmailField(max_length=200, null=True) about = models.CharField(max_length=100, null=True, help_text="Use this field for notes about the customer.") image = models.ImageField(null=True, blank=True) @property def imageURL(self): try: url = self.image.url except: url = 'placeholder.png' return url def __str__(self): return self.name class Post(models.Model): title = models.CharField(max_length=200, null=True) context = models.TextField(max_length=1702, blank=True, validators=[MaxLengthValidator(1702)]) date = models.DateField(("Date"), default=date.today) author = models.ForeignKey( Customer, on_delete=models.CASCADE, null=True ) def __str__(self): return self.title class Answer(models.Model): title = models.CharField(max_length=200, null=True) context = models.TextField(max_length=1702, blank=True, validators=[MaxLengthValidator(1702)]) date = models.DateField(("Date"), default=date.today) author = models.ForeignKey(Customer, on_delete=models.CASCADE, null=True) post = models.ForeignKey(Post, on_delete=models.CASCADE, null=True) def __str__(self): return self.title That means that … -
Django Admin logout page loading instead of custom
I'm following the book Django 3 By Example, and am trying to get a custom log-out page to show when a user logs out. Currently it redirects to the django admin logout page. My logout.html: {% extends "base.html" %} {% block title %}Logged out{% endblock %} {% block content %} <h1>Logged out </h1> <p> You have been successfully logged out. You can log-in again <a href="{% url login %}">here.</a> </p> {% endblock %} urls.py: from django.urls import path from django.contrib.auth import views as auth_views from . import views urlpatterns = [ #post views # path('login/', views.user_login, name='login'), path('login/', auth_views.LoginView.as_view(), name='login'), path('logout/', auth_views.LogoutView.as_view(), name='logout'), path('', views.dashboard, name='dashboard'), ] In my settings I have account app above django.contrib.admin as shown: INSTALLED_APPS = [ 'account.apps.AccountConfig', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.admin', 'django.contrib.staticfiles', ] Not sure what I'm missing here. The login works as expected which makes me think it must be using the registration/logout.html of django.contrib.admin instead of in the account templates folder. I'm not sure from what I understand it should go in order of INSTALLED_APPS. Thanks! -
DJANGO redirect to external url raises CORS error on browser
On my Django view I need to redirect to an external service which I have no control on. But when I do that I get: .....has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. What I understand from the error message the external url is not accepting cross origin requests. But it is a well knows service and being used by many others. Or should I do something on my side? Can anyone help me to understand the problem please? -
How could I ,,catch'' more values through django view?
I want to make a simple questionnaire with two buttons with answers (only one can be active) and I have model of a question and answer, answer should contain an ID of a question, how could I receive the id of that question in my views? I thought of something like data-id = "{{ id }}" and catching it in my view but it does not work html page <form action="." method="post"> {% for q in questions_data %} <ul> <li>{{ q.question }}</li> </ul> {% csrf_token %} <button type="submit" data-id = "{{ q.q_id }}" name="answerButton" value="{{ q.answer1 }}">{{ q.answer1 }}</button> <button type="submit" data-id = "{{ q.q_id }}" name="answerButton" value="{{ q.answer2 }}">{{ q.answer2 }}</button> {% endfor %} </form> views @login_required def select_interests(request): questionnaire_form = InterestSelectionForm() questions_data = InterestQuestion.objects.all() if request.method == 'POST': #question_id = interest = request.POST.get('answerButton') answered = UserInterest() #answered.q_id = question_id answered.selectedInterest = interest answered.save() return render(request, 'account/dashboard.html', {'section': 'dashboard'}) return render(request, 'quiz/quiz_form.html', locals()) -
Two way communication using Chatbot
I want to make a chatbot which can help company manager to assign a task to their employees. For that I need two way communication in which chat bot will be mediator. Example : If manager send a message then it should receive by employee in a bot. and If employee send a message then it should receive by employee in a bot. import os import sys import json import requests from flask import Flask, request app = Flask(__name__) TOKEN = Page_Access_token VERIFY_TOKEN = verification_token params = { "access_token": TOKEN } headers = { "Content-Type": "application/json" } @app.route('/webhook', methods=['GET']) def verification(): # Webhook Verification if request.args.get("hub.challenge"): if not request.args.get("hub.verify_token") == VERIFY_TOKEN: return "Verification token mismatch", 403 return request.args["hub.challenge"], 200 return "Hello", 200 @app.route('/webhook', methods=['POST']) def webhook(): # Messaging Events data = request.get_json() log(data) if data["object"] == "page": for entry in data["entry"]: for messaging_event in entry["messaging"]: if messaging_event.get("message"): #Messaging Event receiveMessage(messaging_event) else: # Unknown Event log("Webhook received unknown messaging_event: " + str(messaging_event)) return "ok", 200 def sendMessage(recipient_id, message_text): # Definition of sendMessage - A function to send Text Messages to user log("sending message to {recipient}: {text}".format(recipient=recipient_id, text=message_text.encode('utf-8'))) # encode('utf-8') included to log emojis to heroku logs message_data = json.dumps({ "recipient": { … -
RecursionError at /logout maximum recursion depth exceeded in django
I just try to make a logout and redirect to home page with but it show error i'm getting what exactly is going wrong in code my views.py file from django.contrib.auth import authenticate ,logout def logout(request): logout(request) return HttpResponseRedirect('/') -
Allow the user to input only a part of django model creaton form (add to form after user submitted it)
How I can add data to form that user submitted ? I want the user to fill in the "name" and "done" in the form and automatically add "user" (creator) and "board" code: #views.py @login_required(login_url='loginPage') def taskAdd(request, pk): board = Board.objects.filter(user=request.user).get(pk=pk) form = AddTaskForm() if request.method == "POST": form = AddTaskForm(request.POST) if form.is_valid(): form.initial['user'] = request.user form.initial['board'] = board # that doesn't seem to work.... form.save() return redirect('insideBoard', pk) context = {'form': form} return render(request, 'tasks/taskAdd.html', context) #forms.py class AddTaskForm(ModelForm): class Meta: model = Task fields = "__all__" exclude = ('user', 'board',) #models.py class Board(models.Model): title = models.CharField(max_length=50, null=True) user = models.ForeignKey(User, null=True, on_delete=models.CASCADE) def __str__(self): return self.title class Task(models.Model): title = models.CharField(max_length=200, null=True) done = models.BooleanField(default=False, null=True) created_at = models.DateTimeField(auto_now_add=True, null=True) user = models.ForeignKey(User, null=True, on_delete=models.CASCADE) board = models.ForeignKey(Board, null=True, on_delete=models.CASCADE) def __str__(self): return self.title -
| Django | how do I keep track of the stocks a user owns, while making a trading website
I don’t know how to approach this issue. Since it’s a trading website I need to keep track of shares a person owns. How do I do that?? Also, I will need to cross-check against that list, later on, to know if they have stock in the right amount that they wanna sell. Use case example:- User_alpha buys 10 apple stock. Now I need my project to know he has 10 Apple shares. Now, he again buys 10 apple stock. Then, user_alpha wants to sell 15 apple stock. We allow him to do that. Then he tries to sell 10 more, an error pops up letting him know he only has 5 left. This is how I imagine it working, I don’t know if it is possible or how to do it. I am inexperienced, please help me out here! Thank you for your time! :) HAPPY NEW YEAR! If you have some extra time please briefly explain the implementation as well. Code[of models] I have written till now(not to solve this problem but in general): from django.db import models # Create your models here. class User_Info(models.Model): name = models.CharField(max_length=200, null=True) phone = models.CharField(max_length=200, null=True) email = models.CharField(max_length=200, null=True) date_created …