Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 … -
How to get username in django_requestlogging
I am using ‘django_requestlogging’ for the log file and I have followed django_requestlogging this link and configured it as per the steps given. I am not getting the username in the log file instead of that I am getting “-”. Please find the code details. step1.Installed application INSTALLED_APPS = [ ------- ------ 'django_requestlogging', ] step2: Created Middleware from django.utils.deprecation import MiddlewareMixin from django_requestlogging.middleware import LogSetupMiddleware as Original class LogSetupMiddleware(MiddlewareMixin, Original): pass step3: used in settings.py 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’, ‘user_visit.middleware.UserVisitMiddleware’, # ‘django_requestlogging.middleware.LogSetupMiddleware’, ‘apple.middleware1.LogSetupMiddleware’ ] step4: Configuration import logging import logging.config LOGGING = { 'version': 1, # Version of logging 'disable_existing_loggers': False, 'filters': { # Add an unbound RequestFilter. 'request': { '()': 'django_requestlogging.logging_filters.RequestFilter', }, }, 'formatters': { 'request_format': { 'format': '%(remote_addr)s "%(request_method)s ' '%(path_info)s %(server_protocol)s" %(http_user_agent)s ' '%(message)s %(asctime)s', }, 'simple': { 'format': '[%(asctime)s] - %(levelname)5s -:%(message)3s -" %(username)5s' }, }, 'handlers': { 'console': { 'level': 'INFO', 'class': 'logging.StreamHandler', 'filters': ['request'], 'formatter': 'simple', }, 'file': { 'level': 'INFO', 'class': 'logging.FileHandler', 'filename': 'Apple00012.log', 'formatter':'simple' }, }, 'loggers': { 'django': { # Add your handlers that have the unbound request filter 'handlers': ['console','file'], 'level': 'DEBUG', 'propagate': True, # Optionally, add the unbound request filter to your # … -
What is the best way to set up a daemon process in django
I am working on an exchange related program that matches buy and sell orders from clients. I am new to django and I am trying to figure out the best way to implement my logic. Suppose I have a coroutine that accepts a stream of client generated data like so: @coroutine #primes coroutine def waiter(q): """ Accepts orders from clients, sorts and puts them in a processing queue """ sell_orders = [] buy_orders = [] while True: size, price, order = yield orderq = sell_orders if order == "sell" else buy_orders orderq.append((size, price, order)) orderq.sort(key = lambda x: x[0], x[1]) #can this be done in redis? q.put(sellOrders[0], buyOrders[0]) And suppose I have a daemon process that checks the queue and processes the data like so: def chef(q): """ Daemon process, checks queue for orders Match orders when buy price is > than sell price """ sleep = 5 while True: if not q.empty(): buy, sell = q.get() buy_price, sell_price = buy[0], sell[0] if buy_price >= sell_price: print("Make Trade") else: time.sleep(sleep) q = Queue(maxsize=0) t = Thread(target = chef, args =(q,) ) t.setDaemon(True) t.start() I can pass orders to the waiters like so: if __name__ == '__main__': m = Waiter(q) buy … -
Django 3.1.4 - AUTH_USER_MODEL refers to model 'users.AppUser' that has not been installed even though app is in INSTALLED_APPS
I've encountered a very odd issue, that I'm suspecting I'll have to put in an issue for with the django team. I've followed the documentation here to great success at setting the following custom user model: apps.users.models.py ... # Here, the genders choices are declared in models.py class Genders(models.TextChoices): UNSPECIFIED = '', _('Unspecified') MALE = 'M', _('Male') FEMALE = 'F', _('Female') # Create your models here. class AppUser(AbstractUser): gender = models.CharField( max_length=6, choices=Genders.choices, default=Genders.UNSPECIFIED, blank=True) birthday = models.DateField(blank=True, null=True) weight = models.DecimalField( max_digits=5, decimal_places=2, null=True, blank=True) @property def age(self): return relativedelta(date.today(), self.birthday).years if self.birthday else None def get_eligable_age_divisions(self) -> 'QuerySet[WeightClass]': query = self.__get_bound_query(self.age) # TODO Genders being in the user models module is causing a circular reference. # move genders to separate module caused the appUser module to appear as not registered # pylint: disable=import-outside-toplevel from apps.divisions.models import AgeDivision return AgeDivision.objects.filter(query) ... apps.divisions.models ... class WeightClass(models.Model): gender = models.CharField( max_length=1, blank=True, choices=Genders.choices, default=Genders.UNSPECIFIED) lower_bound = models.PositiveIntegerField(default=0) upper_bound = models.PositiveIntegerField(default=0) ... settings.py ... INSTALLED_APPS = [ 'apps.users', 'apps.divisions', ... ] AUTH_USER_MODEL = 'users.AppUser' ... The above works with no issues. However, I really don't like my imports anywhere but at the top level, as it adds unnecessary confusion about module dependencies. … -
Django 3 takes only django.po file into consideration: normal?
Django 3 under Windows10 in development environment. A single Django app. Generation of .po file and compilation into .mo files working well. The default filename is django.po. But translation works fine only if translation file is django.mo (compiled from django.po) If filename is changed - I wanted to give it the app name so my_app.po - the compilation works, but the translation process ignores it. I tried with two .po files, one named django.po and the other one my_app.po. Compilation of both is fine, but the translation process only take into account django.mo. If I remove both mo files, switch names (django to my_app and vice-versa), compile to .mo and try, only the new django.mo is taken into account. If none of them is django.po, both are ignored. So only django.mo file (always compile po file(s) so .mo match .po filename) is taken into account. Is there any reason ? Is it possible to modify that behavior ? -
Gunicorn doesn't respond on Heroku
I run a gunicorn server on Heroku with the Django framework, but it doesn't respond and closes a connection. Everything works fine on my Windows computer using the Djagno development server Here is my log: 2021-01-01T16:13:18.000000+00:00 app[api]: Build succeeded 2021-01-01T16:13:39.971142+00:00 app[web.1]: [2021-01-01 16:13:39 +0000] [10] [DEBUG] GET / 2021-01-01T16:13:41.373082+00:00 heroku[router]: at=error code=H13 desc="Connection closed without response" method=GET path="/" host=computer-vision-ml.herokuapp.com request_id=fc6bf181-e15b-4506-8fe5-8714c033406f fwd="83.30.65.205" dyno=web.1 connect=1ms service=1402ms status=503 bytes=0 protocol=https 2021-01-01T16:13:41.376383+00:00 app[web.1]: [2021-01-01 16:13:41 +0000] [21] [INFO] Booting worker with pid: 21 2021-01-01T16:13:41.934138+00:00 app[web.1]: [2021-01-01 16:13:41 +0000] [11] [DEBUG] GET /favicon.ico 2021-01-01T16:13:42.949069+00:00 app[web.1]: [2021-01-01 16:13:42 +0000] [30] [INFO] Booting worker with pid: 30 2021-01-01T16:13:42.943440+00:00 heroku[router]: at=error code=H13 desc="Connection closed without response" method=GET path="/favicon.ico" host=computer-vision-ml.herokuapp.com request_id=30a20795-6f0b-463c-ba6d-5e72368cd1fc fwd="83.30.65.205" dyno=web.1 connect=1ms service=1010ms status=503 bytes=0 protocol=https Procfile: web gunicorn ComputerVision.wsgi --timeout 15 --keep-alive 5 --log-level debug -
Accessing corresponding object in listview when each object has a form
I am using ListView (and also DetailView) to show the same content for several different objects, and each object is shown with a form. As part of the information, I need to know which object they filled the form out for because the object needs to be a part of the data that I grab from the form. Here's the structure of my code: class ObjectListView(LoginRequiredMixin, FormMixin, ListView): model = Object template_name = 'ui/home.html' context_object_name = 'objects' form_class = OrderForm def post(self, request, *args, **kwargs): form = self.get_form() if form.is_valid(): obj = form.save(commit=False) obj.user = request.user.account obj.save() order_type = form.cleaned_data.get('order_type') price = form.cleaned_data.get('price') messages.success(request, f'Your order has been placed.') return redirect('account') -
How do I find each instance of a model in Django
I am trying to iterate through each instance of a model I have defined. Say I have the following in models.py, under the people django app: class foo(models.Model): name = models.CharField(max_length=20, default="No Name") age = models.PositiveSmallIntegerField(default=0) And I have populated the database to have the following data in foo: name="Charley", age=17 name="Matthew", age=63 name="John", age=34 Now I want to work out the average age of my dataset. In another part of the program (outside the people app, inside the project folder), in a file called bar.py that will be set up to run automatically every day at a specific time, I calculate this average. from people.models import foo def findAverageAge(): total = 0 for instance in //What goes here?// : total += instance.age length = //What goes here, to find the number of instances?// average = total / length return average print(findAverageAge) In the code above, the //What goes here?// signifies I don't know what goes there and need help. Before you downvote for lack of research, I have spent hours scouring the Django documentation and have found nothing on this. Maybe I've been looking in the wrong place, or I guess didn't really know what to search. Still new …