Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How would I best handle two modelforms in a single submit/view flow with a FK relation?
I have the below two models # models.py class Applicant(models.Model): """ A table to store all applicants, relates 1-n to an offer """ name = models.CharField(max_length=50) job = models.CharField(max_length=50) start = models.DateField(null=True, blank=True) def __str__(self): return f'{self.name} applying for {self.job} starting {self.start}' class Offer(models.Model): """ A table to store created offers """ # Relations applicant = models.ForeignKey(Applicant, on_delete=models.CASCADE) # Self monthly_raise = models.FloatField() months = models.PositiveIntegerField(validators=[MinValueValidator(1), MaxValueValidator(60)]) start_salary = models.FloatField() In my template I render all fields except for start (which I don't render at all) in the same <form></form> wrapper. Now in my view I want to create new instances for each of the modelforms but only if both are valid. This is what I have which throws NOT NULL constraint failed: planner_offer.applicant_id def render_dashboard_planner(request): site = 'planner' if request.method == 'GET': applicant_form = ApplicantForm() offer_form = OfferForm() context = { 'applicant_form': applicant_form, 'offer_form': offer_form, 'site': site } return render(request, "dashboard/dashboard_planner.html", context) else: # Process the created Offer applicant_form = ApplicantForm() offer_form = OfferForm() form_applicant = ApplicantForm(request.POST) form_offer = OfferForm(request.POST) if form_applicant.is_valid() and form_offer.is_valid(): form_applicant.save(commit=True) form_offer.save(commit=True) context = { 'site': site, 'offer_form': offer_form, 'applicant_form': applicant_form, } return render(request, "dashboard/dashboard_planner.html", context) How would I fix the relation issue and is … -
How to Get Text From Image in Django Web Application using tesseract?
i am building a django web application to extract text from images. i wanna use tesseract for it. but tesseract python code work normally in windows pc and not work in django web application. this is the error when i run python code using html click button tesseract-ocr/tesseract.exe is not installed or it's not in your path. this is the my python code for tesseract in django web app def text1(): global img import pytesseract as tess tess.pytesseract.tesseract_cmd = r'Tesseract-OCR\\tesseract.exe' from PIL import Image def program(): img = Image.open("./static/img/figure-65.png") text = tess.image_to_string(img) print(text) program() text1 function call by html click button and it correctly set to views.py and urls.py This image shows where the tesseract python code and tesseract.exe In imageToText.py have the python code. You can see Tesseract-OCR Folder, that's where **tesseract.exe** have. urls.py of web app from django.urls import path from . import views urlpatterns = [ path('', views.home, name="home"), path('openC', views.openC, name="openC"), path('text1', views.text2, name="text1"), ] urls.py of main web project from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static from img2text.settings import MEDIA_ROOT urlpatterns = [ path('admin/', admin.site.urls), path('', include("imgtext.urls")) ]+ static(settings.MEDIA_URL, document_root=MEDIA_ROOT) views.py from django.shortcuts import render,redirect … -
What plugins in PYCHARM should you add for DJANGO?
I want to use PYCHARM for DJANGO and have seen in VS CODE plugins for the visibility of the code as: https://marketplace.visualstudio.com/items?itemName=batisteo.vscode-django Django - Visual Studio Marketplace Extension for Visual Studio Code - Beautiful syntax and scoped snippets for perfectionists with deadlines do you know which plugins I should add? thank you!! -
Django Rest Framework Allow a request to set a foreign key Field in CreateAPIView
A thread belongs to a board. So I would like the ThreadList view to accept a POST request with the foreign key board. What I have attempted results in an error. AssertionError: Relational field must provide a queryset argument, override get_queryset, or set read_only=True serializers.py class ThreadSerializer(serializers.ModelSerializer): post = PostSerializer(many=True, read_only=True) # board = serializers.ReadOnlyField(source='board.id') board = serializers.PrimaryKeyRelatedField(source='board.id') class Meta: model = Thread fields = ['id', 'title', 'post', 'board'] views.py class ThreadList(generics.ListCreateAPIView): permission_classes = [permissions.IsAuthenticatedOrReadOnly] def perform_create(self, serializer): serializer.save(thread_admin=self.request.user) queryset = Thread.objects.all() serializer_class = ThreadSerializer models.py class Board(models.Model): name = models.CharField(max_length=25, unique=True) created = models.DateTimeField(auto_now_add=True) board_admin = models.ForeignKey('auth.User', on_delete=models.CASCADE, related_name='board_admin') board_moderator = models.ManyToManyField(User, related_name='board_moderator') class Meta: ordering = ['created'] class Thread(models.Model): title = models.CharField(max_length=250) created = models.DateTimeField(auto_now_add=True) thread_admin = models.ForeignKey('auth.User', on_delete=models.CASCADE, related_name='thread') board = models.ForeignKey(Board, on_delete=models.CASCADE, related_name="thread") class Meta: ordering = ['created'] -
AttributeError: 'WSGIRequest' object has no attribute 'query_params'
I'm trying to pull data from the site on the backend side everything will work: link from where I pull all the data https://swapi.dev/api/people count = {'count': 0, "next_page": 1, 'dates': [],} starwars = [count, ] # class StarView(APIView): # def get(self, request): # page = request.query_params.get('page', 1) # if starwars[0]['next_page'] == int(page): # url = f'https://swapi.dev/api/people/?page={page}' # response = requests.get(url).json() # starwars.append(response['results']) # starwars[0]['count'] += 10 # starwars[0]['next_page'] += 1 # starwars[0]['dates'].append(datetime.today()) # with open('story.csv', 'w') as file: # file.write(str(starwars[0])) # for i in range(1, len(starwars)): # for j in starwars[i]: # file.write('\n') # file.write(str(j)) # return Response(starwars, status=status.HTTP_200_OK) # return Response({"error": "Enter valid page"}) But as soon as I decided to create a template def index ..... for the place of this code, I get this error how to fix it (AttributeError: 'WSGIRequest' object has no attribute 'query_params') def index(request): if request.method == "GET": page = request.query_params.get('page', 1) if starwars[0]['next_page'] == int(page): url = f'https://swapi.dev/api/people/?page={page}' response = requests.get(url).json() starwars.append(response['results']) starwars[0]['count'] += 10 starwars[0]['next_page'] += 1 starwars[0]['dates'].append(datetime.today()) with open('story.csv', 'w') as file: file.write(str(starwars[0])) for i in range(1, len(starwars)): for j in starwars[i]: file.write('\n') file.write(str(j)) return render(request,('index.html')) return Response({"error": "Enter valid page"}) What am I even trying to do? I … -
Fetched Json data from API is undefined
I m trying to populate a detail product page with data fetched from my API using useEfect() and useState() hooks in ReactJS, but everytime when i want to print into the console the object fetched it gives me a message with undefined, please help me . API model: from django.db import models class Product(models.Model): id = models.IntegerField(null=False, default=0, primary_key=True) product_name = models.CharField(max_length=60, null=False, default='no name') category = models.CharField(max_length=60, null=False, default='misc_product') author = models.CharField(max_length=60, null=False, default='anonim') collection = models.CharField(max_length=60, null=False, default='anonim') family = models.CharField(max_length=60, null=False, default='anonim') image_path = models.CharField(max_length=160, null=False, default='') likes_no = models.IntegerField(null=False, default=0) price = models.FloatField(null=False, default=0.00) def __str__(self): return self.product_name` API Serializer from rest_framework import serializers from .models import Product class ProductSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Product fields = ( 'id', 'product_name', 'category', 'author', 'collection', 'family', 'image_path', 'likes_no', 'price', ) API Views from rest_framework import viewsets from rest_framework.views import APIView from .serializers import ProductSerializer from .models import Product from rest_framework.response import Response from rest_framework import status class ProductViewSet(APIView): queryset = Product.objects.all() serializer_class = ProductSerializer @classmethod def get_extra_actions(cls): return [] def post(self, request): serializer = ProductSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response({"status": "success", "data": serializer.data}, status=status.HTTP_200_OK) else: return Response({"status": "error", "data": serializer.errors}, status=status.HTTP_400_BAD_REQUEST) def get(self, request, id=None): if id: item … -
Django production with Apache in Ubuntu not show image
I want to config my django project in Ubuntu server which use Apache but it not show image. I edit file settings.py like this. settings.py DEBUG = False STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_URL='/media/' MEDIA_ROOT=os.path.join(BASE_DIR,'static','media') I show image in html file like this. index.html {% load static %} {% block content %} <img src="{% static '/media/images/logo.png' %}"> {% endblock %} I set apache file in path /etc/apache2/sites-available/000-default.conf like this. <VirtualHost *:80> ServerName myweb.com DocumentRoot /home/user/myproject_dir/myproject ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined Alias /static /home/user/myproject_dir/myproject/static <Directory /home/user/myproject_dir/myproject/static> Require all granted </Directory> <Directory /home/user/myproject_dir/myproject/myproject> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess myproject_dir python-path=/home/user/myproject_dir/myproject python-home=/home/user/myproject_dir/myproject_env WSGIProcessGroup myproject_dir WSGIScriptAlias / /home/user/myproject_dir/myproject/myproject/wsgi.py </VirtualHost> I upload image to path like this. /home/user/myproject_dir/myproject/static/media/images/logo.png I use command collectstatic and restart apache service but it not show image in my website. How to fix it? -
how can i create a table entry in django views
I want to make a system of likes on the site, and I need to create an entry in the table on the button. When a person clicks on like, the table writes row 1 and when dislike 0 views.py def forum(requset): model = Quetions.objects.all() answer = Answer.objects.all() count = Answer.objects.all().count() count_answer = Quetions.objects.all().count() paginator = Paginator(model, 1) # Show 25 contacts per page. page_number = requset.GET.get('page') question_id = requset.GET.get('id',False) page_obj = paginator.get_page(page_number) requestanswer = requset.GET.get('id',False) like_disli = like.objects.filter(like_dislike = "1").count() dislike = like.objects.filter(like_dislike = "0").count() createlike = objects = { 'model': page_obj, 'answer':answer, 'count':count, 'count_question':count_answer, 'page_obj':page_obj, 'question':question_id, 'id':model, 'request':requestanswer, 'like':like_disli, 'dislike':dislike, 'createlike':createlike, } return render(requset,'forum.html',objects) forum.html <span> <i class="fas fa-thumbs-up" style="color: blue;margin-right: 5px;" onclick="incrementClick()"></i>{{like}}<i class="fas fa-thumbs-down" style="color: red;margin-right: 5px;margin-left: 10px;" onclick="dislikeclick()"></i>{{dislike}} </span> {% block js %} <script> var a = "{{createlike}}" function incrementClick() { a } function dislikeclick() { dislikedisplay(++dislikecounter); } function updateDisplay(val) { document.getElementById("counter-label").innerHTML = val; } function dislikedisplay(val){ document.getElementById("counter").innerHTML = val } </script> {% endblock js %} tell me how to do it??? -
How can I enable directions on embeded google map in my web app
I am new in django and I am trying to create a web app for bycicle roads in a specific city.Till now I have managed to add a Map of the city in my project.Bellow a piece of the HTML: ''' <iframe width="100%" height="100%" frameborder="0" style="border:0" referrerpolicy="no-referrer-when-downgrade" src="https://www.google.com/maps/embed/v1/place?key=AIzaSyB50AmUn73pxdoVuVhRAkjAjnhGjLp7ymM&q=streets+in+Sofia" allowfullscreen> </iframe> ''' The question is following: I have the Directions button on the map but it redirects to google.maps. I want to make the directions(Start and Endpoint) to appear right over the map(on the same page). Is this possible and how can I do this ? Thank you! -
Setting variable is not being set up during testing middleware (p
settings.py MY_VAR = os.get("MY_VAR", False) custom_middleware.py from my_proj.settings import MY_VAR from django.core.exceptions import MiddlewareNotUsed class CustomMiddleware: def _init_(self, get_response): if MY_VAR == 'False': raise MiddlewareNotUsed self.get_response = get_response def __call__(self, request): if MY_VAR == 'True': #My custom logic return response = self.get_response(request) return response test_custom_middleware.py import os from unittest.mock import Mock from api.middlewares.custom_middleware import CustomMiddleware class TestLCustomMiddleware: def test(self, settings): request = Mock() settings.MY_VAR = 'True' assert settings.MY_VAR with patch.dict('os.environ', {'MY_VAR': 'True'}): assert 'MY_VAR' in os.environ middleware = CustomMiddleware(get_response='response') middleware(request) In CustomMiddleware I always get "False" in MY_VAR variable of settings. How can I set it up? -
Is it possible to create a formset in a formset?
For an example I wanted to create quiz using formsets. User can add more questions and more answers to each question too(max=4). -
Django Select a valid choice error while poulate it via objects.none()
I am currently having issue to ModelChoiceFiled. I initilize it in form via objects.none() but in html I update it via ajax. when I want to save my form I encounter the " select a valid choice ". Forms: woPart = forms.ModelChoiceField(label="نام کاربر",queryset=Stock.objects.none(),required=False) -
Why save() method need to self argument in django?
I am trying to solve this problem for over 3 days but can't solve it yet. I know self use for a method that is under a class, but I am working with method base view so why this error occurs when I try to save the OrderItem model? models.py class OrderItem(BaseModel): user = models.ForeignKey(User, on_delete=models.CASCADE) customer = models.ForeignKey(Customer, on_delete=models.CASCADE) cart = models.ManyToManyField(Cart, blank=True) name = models.CharField(max_length=200) district = models.ForeignKey(District, on_delete=models.CASCADE) city = models.CharField(max_length=200) postal_code = models.SmallIntegerField() area = models.TextField() phone = models.CharField(max_length=12) status = models.CharField(max_length=20, choices=STATUS_CHOICE, default="accepted",blank=True, null=True) email = models.EmailField() def __str__(self): return self.user.email views.py def checkout(request): context={} subtotal =0 forms = OrderItemForm() context['forms'] = forms if request.user.is_authenticated: user = request.user cart = Cart.objects.filter(user=user).order_by('-id') for product in cart: subtotal += product.total_cost context['subtotal'] = subtotal customer = Customer.objects.get(user=user) if request.POST: form = OrderItemForm(request.POST) if form.is_valid(): instance = OrderItemForm.save(commit=False) instance.user = user instance.customer = customer instance.cart = cart instance.save() else: messages.warning(request, form.errors) return render(request, 'checkout.html', context) command-line error: response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\bitspirits\rndm\shop\views.py", line 76, in checkout instance = OrderItemForm.save(commit=False) TypeError: save() missing 1 required positional argument: 'self' -
Writing test for race condition
I want to write unit test to check if race condition happens when multiple users send request at the same time. I'm using pytest. I have tried threading module of python and it didn't work. What is the standard solution? -
Django celery and heroku
I have configured celery to be deployed in heroku, all Is working well, in fact in my logs at heroku celery is ready to handle the taks. Unfortunately celery doesn't pick my tasks I feel there is some disconnection, can I get some help? -
Attribute Error at/ 'str' object has no attribute 'makefile'
I'm learning Django and got this error in my first code itself. I was trying for just Hello world type of program using Django, everything was perfect but got this error 'str' object has no attribute 'makefile' -
Tailwind purgecss with django forms?
I have a django project with a forms.py where I want to style the fields with tailwind. However, I can't figure out how to get purgecss to not remove the classes I have in forms.py. Is there a way to dynamically check python files as well, or do I have to resort to whitelisting them? # users/forms.py class SignUpForm(UserCreationForm): # ... class Meta: model = User fields = ('username', 'email', 'password1', 'password2', ) widgets = { 'username': forms.TextInput(attrs={ 'class': 'bg-gray-300' # how to not purge this class? }) } // tailwind.config.js module.exports = { content: [ // ... '/**/forms.py' // this doesn't work ], // ... -
Carousel with backend data showing all images or no images
I am running a Django application where I receive the list of images and in my template, I have the following code for Carousel. The issue is if I use this class "carousel-inner active" while iterating all images are set active and all images are shown on a single screen, if not if I remove active and just keep carousel-inner no image is shown <div id="demo" class="carousel slide" data-bs-ride="carousel"> <!-- Indicators/dots --> <div class="carousel-indicators"> <button type="button" data-bs-target="#demo" data-bs-slide-to="0" class="active"></button> <button type="button" data-bs-target="#demo" data-bs-slide-to="1"></button> </div> <!-- The slideshow/carousel --> <div class="carousel-inner active"> {% for image in data.images %} <div class="carousel-item active"> <img src="{{ image }}" alt="image 1" class="d-block" style="width:100%"> </div> {% endfor %} <!-- Left and right controls/icons --> <button class="carousel-control-prev" type="button" data-bs-target="#demo" data-bs-slide="prev"> <span class="carousel-control-prev-icon"></span> </button> <button class="carousel-control-next" type="button" data-bs-target="#demo" data-bs-slide="next"> <span class="carousel-control-next-icon"></span> </button> </div> -
Django Streaming Videos from Mobile Devices not Working Properly
Django server does not play videos properly on mobile devices. Video seek options are not available. It works fine if we use media files from another domains but files from own server are not working correctly. Forward, rewind and seek options are not accessible <video id='main-video' controls style="width:100%;"> <source src='{{ video_format.url }}' title='{{ name }}' type='video/mp4' /> </video> Should I change any Django core settings? I have built the server using Nginx + Django + Gunicorn. -
Model ID in a for loop (django jinja) how do I set the pk value
I am trying to figure out how I can get the model ID from the for loop in the html/jinja to be set as the cert_id in views.py so that I can update that specific model by clicking the update button I am not sure if there is an easier way i.e. passing the 'cert.id' back to django some other way any help would be excellent thank you, littlejiver detail.html <div id="Certificate" class="tabcontent"> <div class="cert-btn-div"> <button onclick="showAddSiteForm()" id="sitebtn" class="btn"> Add Certificate + </button> <div class="form-add-site" id="form-add-site-js"> <form method="post" enctype="multipart/form-data"> {% csrf_token %} <p> {{ form.department.label }}: {{ form.department }} {{ form.licence.label }}: {{ form.licence }} Exp. Date: {{ form.exp }} {{ form.file.label }}: {{ form.file }} </p> <button name="add_site_btn" type="submit">Create</button> </form> </div> </div> <table class="cert-table"> <tr> <th>Dpt:</th> <th>Licence:</th> <th>Exp. Date:</th> <th>Upload Date:</th> <th>File:</th> <th></th> <th></th> <th></th> </tr> <tr> {% for cert in list_of_certs %} <td>{{ cert.department }}</td> <td>{{ cert.licence }}</td> <td>{{ cert.exp }}</td> <td>{{ cert.ul_date }}</td> <td>{{ cert.file }}</td> <div class="upload-tds"> <td> <button class="btn sitebtn" onclick="showUpdateCertForm({{cert.id}})" id="sitebtn{{cert.id}}">Update File</button> </td> <td> <div class="upload-tds-hidden" id="form-update-cert-js{{cert.id}}"> <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form.file }} <button class="btn" name="update_btn" type="submit">Update</button> </form> <div> <button class="btn sitebtn" onclick="showUpdateCertForm({{cert.id}})" id="cancelbtn{{cert.id}}">Cancel</button> </div> </div> </td> </div> </div> </tr> {% … -
How to predict error when saving utf8 chars in latin-1 mysql table via django?
My setup is using python3+, django 3.2 with mysql 5.7 on an AWS Amazon linux instance. When I originally created my database and tables, I did not specify a particular charset/encoding. So, I read the following post and determined that my tables and columns are currently latin1: How do I see what character set a MySQL database / table / column is? I have also read this post to try and understand the differences between what the client uses as encoding and what the table/database is using -- this allows the client to save non-latin1 chars in a mysql table with latin1 charset: MySQL 'set names latin1' seems to cause data to be stored as utf8 Here is some code to show what I am trying to do: # make a new object mydata = Dataset() # set the description. This has a few different non-latin1 characters: # smart quotes, long dash, dots over the i mydata.description = "“naïve—T-cells”" # this returns an error to prove to myself that there are non-latin1 chars in the string mydata.description.encode("latin-1") # Traceback (most recent call last): # File "<console>", line 1, in <module> # UnicodeEncodeError: 'latin-1' codec cant encode character '\u201c' in position … -
Django sending data from outside consumer class
I am trying to get use Django channels to send data over a websocket to my react native application from django. I have read all the available documentation on this subject on Django and have went through numerous stackoverflow posts, but I don't think they are applicable to me because they use redis and I decided not to use redis. Whenever I try to send data right now, nothing sends. These are my files. models.py from django.db import models import json from .consumers import DBUpdateConsumer from django.db.models.signals import post_save from django.dispatch import receiver from channels.layers import get_channel_layer from asgiref.sync import async_to_sync channel_layer = get_channel_layer() class Connect(models.Model): id = models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID') neighborhood = models.CharField(max_length=50, choices=neighborhood_choices, default='all') first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) email = models.CharField(max_length=100) phone = models.CharField(max_length=50) def save(self, *args, **kwargs): super().save(self, *args, **kwargs) print("def save") async_to_sync(channel_layer.send)("hello", {"type": "something", "text": "hellooo"}) class Meta: managed = False db_table = 'connect' settings.py CHANNEL_LAYERS = { "default": { "BACKEND": "channels.layers.InMemoryChannelLayer" } } consumers.py import json from channels.generic.websocket import AsyncJsonWebsocketConsumer #used https://blog.logrocket.com/django-channels-and-websockets/ #https://channels.readthedocs.io/en/latest/topics/consumers.html class DBUpdateConsumer(AsyncJsonWebsocketConsumer): async def connect(self): self.send_message(self, "UPDATE") await self.accept() await self.send(text_data=json.dumps({ "payload": "UPDATE", })) print("connect!") async def disconnect(self, close_code): print("Disconnected") async def receive(self, text_data): """ Receive message from WebSocket. … -
Unable to update/delete item from table even with on_delete=CASCADE
I am trying to make a Cooking Recipe Portal DB and none of the DELETE queries work for me. Here are my tables/models related to the error: class Ingredient(models.Model): ingredientid = models.IntegerField(primary_key=True) name = models.CharField(max_length=255) type = models.CharField(max_length=255) class IngredientRecipe(models.Model): ingredientid = models.ForeignKey("Ingredient", to_field="ingredientid", on_delete=models.SET_NULL, null=True) recipeid = models.ForeignKey("Recipe", to_field="recipeid", on_delete=models.SET_NULL, null=True) amount = models.CharField(max_length=255) class Meta: unique_together = ("ingredientid", "recipeid") class IngredientNutrition(models.Model): nutritionid = models.IntegerField(null=True, blank=True) ingredientid = models.ForeignKey("Ingredient", to_field="ingredientid", on_delete=models.CASCADE) #ingredientid = models.OneToOneField(Ingredient, on_delete=models.CASCADE) portionsize = models.FloatField(max_length=24) calories = models.IntegerField() fat = models.IntegerField() protein = models.IntegerField() sodium = models.IntegerField() carbs = models.IntegerField() class Meta: unique_together = (("nutritionid", "ingredientid"), ) Issue: Say i want to delete ingredient.ingredientID = 20 or ingredient.name = 'Corn Starch', it won't let me delete because ingredientID = 20 is still referenced by the table IngredientNutrition. I have on__delete=CASCADE. I tried altering the parameters inside the models.ForeignKey and changed parameters in various keys in different tables to see if it allowed me to delete. -
Django cache real-time data with DRF filtering and sorting
I'm building a web app to manage a fleet of moving vehicles. Each vehicle has a set of fixed data (like their license plate), and another set of data that gets updated 3 times a second via websocket (their state and GNSS coordinates). This is real-time data. In the frontend, I need a view with a grid showing all the vehicles. The grid must display both the fixed data and the latest known values of the real-time data for each one. The user must be able to sort or filter by any column. My current stack is Django + Django Rest Framework + Django Channels + PostgreSQL for the backend, and react-admin (React+Redux+FinalForm) for the frontend. The problem: Storing real-time data in the database would easily fulfill all my requirements as I would benefit from built-in DRF and Django's ORM sorting/filtering, but I believe that hitting the DB 3 times/sec for each vehicle could easily become a bottleneck when scaling up. My current solution involves having the RT data in python objects that I serialize/deserialize (pickle) into/from the Django cache (REDIS-backed) instead of storing them as models in the database. However, I have to manually retrieve the data and DRF-serialize … -
Django, how can I show variables in other model class?
I'm learning Django and I'm trying to understand its logic. There are 2 models I created. I am designing a job listing page. The first model is "Business". I publish the classes inside this model in my html page and for loop. {% job %} {% endfor %}. But inside my second model in this loop I want to show company_logo class inside "Company" model but I am failing. Methods I tried to learn; 1- I created a second loop inside the job loop, company loop, and published it failed. 2- I assigned a variable named company_list to the Job class on the views page and made it equal to = Company.objects.all() but it still fails. Here are my codes. models.py from django.db import models from ckeditor.fields import RichTextField from djmoney.models.fields import MoneyField JobTypes = ( ('Full-Time', 'Full-Time'), ('Part-Time', 'Part-Time'), ('Internship', 'Internship'), ('Temporary', 'Temporary'), ('Government', 'Government') ) class Job(models.Model): job_title = models.CharField( max_length=100, null=True) job_description = RichTextField() job_application_url = models.URLField(unique=True) job_type = models.CharField(max_length=15, choices=JobTypes, default='Full-Time') #job_category job_location = models.CharField( max_length=100) job_salary = MoneyField(max_digits=14, decimal_places=4, default_currency='USD') created_date = models.DateTimeField(auto_now_add=True) featured_listing = models.BooleanField( default=False) company = models.ForeignKey( "Company", on_delete=models.CASCADE) def __str__(self): return f"{self.company}: {self.job_title}" class Company(models.Model): created_date = models.DateTimeField(auto_now_add=True) company_name = models.CharField(max_length=100, …