Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
In Django why the error "TypeError at / Field 'fees' expected a number but got [[0, 0.26], [50000, 0.24], [100000, 0.22], ..."?
I am trying to figure out how to get in Django a sequence of strings, an integer, and an array of integers or numbers from a Kraken API. I went through other examples here and created the code below. The strings of my code return properly the values, however the arrays of integers return an error. How can i solve this error and gain control over every part of this API content? views.py i marked the variables that "return OK" and the ones that do not return properly are "NOT OK" from django.shortcuts import render from meal_app.models import Kraken import requests def get_krakens(request): all_krakens = {} url ='https://api.kraken.com/0/public/AssetPairs' response = requests.get(url) data = response.json() for i in data['result'].values(): kraken_data = Kraken( altname = i['altname'], # string return OK wsname = i['wsname'], # string return OK aclass_base = i['aclass_base'], # string return OK base = i['base'], # string return OK aclass_quote = i['aclass_quote'], # string return OK quote = i['quote'], # string return OK lot = i['lot'], # string return OK pair_decimals = i['pair_decimals'], # integer return OK lot_decimals = i['lot_decimals'], # integer return OK lot_multiplier = i['lot_multiplier'], # integer return OK # leverage_buy = i['leverage_buy'], # Array of integers NOT … -
(Django) (Factory Boy) (Errno 13) Permission denied
So, I am a complete beginner to Django and am trying to figure out how to populate the database with random data. When I try to run py manage.py setup_test_data the following error occurs from seller.factories import * File "C:\Users\Suyash Singh\Desktop\SwaadBackend1\seller\factories.py", line 13, in <module> f = open(r"C:\Users\Suyash Singh\Desktop\SwaadBackend1\staticfiles\dish", 'r+') PermissionError: [Errno 13] Permission denied: 'C:\\Users\\Suyash Singh\\Desktop\\SwaadBackend1\\staticfiles\\dish' #factories.py import factory import faker from faker import Faker from factory.base import Factory from factory.declarations import SubFactory from factory.django import DjangoModelFactory import random from core.models import User from seller.models import Dish, Restaurant fake = Faker() f = open(r"C:\Users\Suyash Singh\Desktop\SwaadBackend1\staticfiles\dish", 'r+') f1 = open(r"C:\Users\Suyash Singh\Desktop\SwaadBackend1\staticfiles\logo", 'r+') CATEGORIES = [ "Sweets", "Rolls", "Kebabs", "Chaat", "Paneer", "Pizza", "Chicken", "Healthy", "Biryani", "Shawarma", "Thali", "Momos", "Burger", "Dal", 'Dosa', "Chaap", ] MEAL_TIME = [ "Breakfast", "Lunch", "Dinner" ] class Provider(faker.providers.BaseProvider): def dish_category(self): return self.random_element(CATEGORIES) def dish_meal_time(self): return self.random_element(MEAL_TIME) fake.add_provider(Provider) class DishFactory(DjangoModelFactory): class Meta: model = Dish photo = factory.django.ImageField(from_file= f, width=500, height=500) restaurant = factory.SubFactory('seller.factories.RestaurantFactory') price = random.randint(50, 600) title = factory.Faker('dish_category') veg = random.choice([True, False]) category = factory.Faker('dish_category') meal_time = factory.Faker('dish_meal_time') class RestaurantFactory(DjangoModelFactory): class Meta: model = Restaurant user = SubFactory('seller.factories.UserFactory') rest_name = factory.Faker('name') phone = fake.phone_number() address = fake.address() logo = factory.django.ImageField(from_file= f1, width=500, height=500) class UserFactory(DjangoModelFactory): … -
Dynamically add lookup field suffix to lookup field
I currently have this pretty standard code block in my views.py. statsign is a form value, as well as statinput. My model field I want to filter my queryset players by is called nba_avg_rating if statsign == '>=' and len(statinput) > 0: players = players.filter(nba_avg_rating__gte=float(statinput)).order_by(sort) elif statsign == '<=' and len(statinput) > 0: players = players.filter(nba_avg_rating__lte=float(statinput)).order_by(sort) elif statsign == '=' and len(statinput) > 0: players = players.filter(nba_avg_rating__exact=float(statinput)).order_by(sort) As you can see, currently my logic checks the statsign for a condition, filters by model field + the suffix, i.e. >= would result in filtering by nba_avg_rating__gte, so on and so forth. My goal is to make this a dynamic process, in which I consolidate this process into one line. I have a field lookup dictionary like so field_lookup = { '>=': '__gte', '<=': '__lte', '=': '__exact' } And then I iterate through, appending the suffix to the field name, in some code like below. for item in field_lookup.items(): if statsign == item[0] and len(statinput) > 0: players = players.filter((nba_avg_rating + item[1])=float(statinput)).orderby(sort) Now obviously the above code doesn't work, because nba_avg_rating is an expression. I can concatenate the suffix to nba_avg_rating as a string and then wrap it in eval, but alas, … -
Setting ModelChoiceFilter initial
I am currently trying to set the initial for my Category filter based on ther subcategory selected from my home template. index.html {% for category in Category_list %} <div class="col-lg-3 offset-lg-0 col-md-5 offset-md-1 col-sm-6 col-6"> <div class="category-block"> <div class="header"> <i class="fa fa-laptop icon-bg-1"></i> <h4>{{category}}</h4> </div> <form method="GET" action="{% url 'Product-search' %}"> <ul class="category-list" > {% for sub_cat in category.subcat.all %} <li> <button type="submit" class="subcat-button" name="subcategory" value={{ sub_cat.id }} > {{sub_cat}} </button> <span>{{sub_cat.product.count}}</span> </li> {% endfor %} </ul> <form> </div> </div> <!-- /Category List --> {% endfor %} product-search.html I have alot more filters on this page but Im trying to just set the intial for filter.form.category for the subcategory selected on the homepage. <div class="advance-search"> <div class="form-row"> <div class="form-group col-md-4"> {{filter.form.q}} </div> <div class="form-group col-md-3"> {{filter.form.category}} </div> <div class="form-group col-md-3"> {{filter.form.city}} </div> <div class="form-group col-md-2"> <button type="submit" class="btn btn-primary">Search Now</button> </div> </div> </div> filters.py class ProductFilter(django_filters.FilterSet): q = django_filters.CharFilter(widget=forms.TextInput(attrs={'class': 'form-control my-2 my-lg-0', 'id': "inputtext4", 'placeholder': 'What are you looking for'}), method='my_custom_filter', label="Search") city = django_filters.CharFilter(widget=forms.TextInput(attrs={'class': 'form-control my-2 my-lg-0', 'id': "inputtext4", 'placeholder': 'City'}), method='City_filter', label="City") Manufacturer = django_filters.CharFilter(widget=forms.TextInput(attrs={'class': 'form-control my-2 my-lg-0', 'id': "inputtext4", 'placeholder': 'Manufacturer'}), method='Manufacturer_filter', label="Manufacturer") model = django_filters.CharFilter(widget=forms.TextInput(attrs={'class': 'form-control my-2 my-lg-0', 'id': "inputtext4", 'placeholder': 'Model'}), method='Model_filter', label="Model") category = … -
How to ensure if transaction was committed before returning API request?
I use django with ATOMIC_REQUESTS=True. It works fine, but for some cases it causing me issues. For example I have a flow: Call an API, create an object id DB and return it's id. Call another API, using id from the previous step, and create another object in DB. Sometimes step 2 fails, because transaction from the step 1 is not yet committed and I got an error that object doesn't exist. I cannot manually call transaction.commit() before return Response() statement as I rely on ATOMIC_REQUESTS from a box. I can add try, except to the step 2, but the code will look ugly, because it will require to call sleep() for a couple seconds, than try again. Also I'll need to determine how many tries should I have, which can lead to long response time or even to timeout error. Also I can disable ATOMIC_REQUESTS and use atomic transactions manually, but it's not a preferable solution as I'll need to do a lot of refactoring. Does anyone encountered such behavior? -
How to create private chat room consummer with django chennals?
My goal is to create a consumer which provides us with the functionality of private chat. In private chat, There should be two users who exchange messages. Write now anyone can see anybody's message this what I'm trying to fix. consumer.py # chat/consumers.py import json from channels.generic.websocket import AsyncWebsocketConsumer class ProjectConsumer(AsyncWebsocketConsumer): async def connect(self): parameter =self.room_name = self.scope['url_route']['kwargs']["username"] print("url_parameter ",parameter) self.project_name = parameter # Join room group await self.channel_layer.group_add( self.project_name, self.channel_name ) await self.accept() async def disconnect(self, close_code): # Leave room group await self.channel_layer.group_discard( self.project_name, self.channel_name ) # Receive message from WebSocket async def receive(self, text_data): text_data_json = json.loads(text_data) sender = text_data_json['sender'] receiver = text_data_json['receiver'] message = text_data_json['message'] object = { 'sender':sender, 'receiver':receiver, 'message':message, } # Send message to room group await self.channel_layer.group_send( self.project_name, { 'type': 'sent', #function name as an event type 'object': object #function parameters as an event object } ) # Receive message from room group async def sent(self, event): sender = event['object']["sender"] receiver = event['object']["receiver"] message = event['object']["message"] # Send message to WebSocket await self.send(text_data=json.dumps({ 'sender':sender, 'receiver':receiver, 'message':message, })) In advance, thank you so much if you spend time reading this and answer. -
How to call custom functions from models.py django
I'm building a custom function to pull the data from mongodb and want to see the data what it is look like before the manipulation. say I have a function to request the data from mongodb Here is how my models.py looks like from bson import json_util from django.db import models from django.http import JsonResponse from pymongo import MongoClient from bson.json_util import dumps from bson.json_util import loads import json import pymongo def data_pull(request): request_data = request.POST.get('Hello', None) if __name__ == "__main__": data_pull(request) to run the models.py I do python models.py from the command line but getting this error NameError: name 'request' is not defined So basically I want to test this data_pull function from models.py and see that what the data looks like or even calling. How can I feed this request call into the function and see the output from commandline ? -
Buildpack error on deploy django to digital ocean
I try to deploy my app on digitalocean but get an error. Here is part of the deploy process. [2021-11-09 14:34:45] => Initializing build [2021-11-09 14:34:45] => Retrieving source code to /workspace [2021-11-09 14:34:45] => Selecting branch "main" [2021-11-09 14:34:50] => Checking out commit "e7ce2c3730b71e7a92b49cdbd75c60129ecf9cbb" [2021-11-09 14:34:53] => Got source_dir: / [2021-11-09 14:34:53] => Using workspace root /workspace [2021-11-09 14:34:53] [2021-11-09 14:34:53] => Building app using buildpacks [2021-11-09 14:34:54] => Injecting app environment variables: [2021-11-09 14:34:54] DJANGO_SUPERUSER_PASSWORD DJANGO_SECRET_KEY DJANGO_SUPERUSER_EMAIL DJANGO_SUPERUSER_USERNAME POSTGRES_HOST POSTGRES_USER POSTGRES_PORT DJANGO_ALLOWED_HOST POSTGRES_PASSWORD DATABASE_URL DEBUG POSTGRES_DB DISABLE_COLLECTSTATIC [2021-11-09 14:34:54] => Running buildpack detection [2021-11-09 14:34:54] [2021-11-09 14:34:54] 3 of 4 buildpacks participating [2021-11-09 14:34:54] digitalocean/python-appdetect 0.0.2 [2021-11-09 14:34:54] heroku/python 0.192.4 [2021-11-09 14:34:54] digitalocean/procfile 0.0.3 [2021-11-09 14:34:54] [2021-11-09 14:34:54] For documentation on the buildpacks used to build your app, please see: [2021-11-09 14:34:54] Python: https://do.co/apps-buildpack-python [2021-11-09 14:34:55] [2021-11-09 14:34:55] => Building app [2021-11-09 14:34:55] [2021-11-09 14:34:55] -----> Installing python-3.9.4 [2021-11-09 14:34:58] -----> Installing pip 20.1.1, setuptools 47.1.1 and wheel 0.34.2 [2021-11-09 14:35:05] -----> Installing SQLite3 [2021-11-09 14:35:19] rm: cannot remove '/workspace/.heroku/python/apt/state/lists': Directory not empty [2021-11-09 14:35:19] Sqlite3 failed to install. The tail of the process is here. [2021-11-09 14:36:49] yaml: line 3: could not find expected ':' [2021-11-09 14:36:49] … -
Not implemented alter command for SQL ALTER TABLE "annotator_annotationmodel" ADD COLUMN "hospital_id" int NOT NULL
Getting this error after doing migrate in django rest framework backend server models.py file class Hostipal(models.Model): hospitalId = models.CharField(max_length=15, unique=True) hospitalName = models.CharField(max_length=255, default='') hospitalAddress = models.CharField(max_length=255, default='') def __str__(self): return self.hospitalName class AnnotationModel(models.Model): name = models.CharField(max_length=255, default='') model_path = models.CharField(max_length=255, default='') hospital = models.ForeignKey(Hostipal, on_delete=models.CASCADE) def __str__(self): return self.name class ModelPool(models.Model): name = models.CharField(max_length=255, default='') modelsList = models.ManyToManyField(AnnotationModel, related_name="modelpool") hospital = models.ForeignKey(Hostipal, on_delete=models.CASCADE) def __str__(self): return self.name what I am trying to build every hospital has many AnnotationModels and ModelPools. each AnnotationModel may belong to many model pools. Hence AnnotationModel has a hospital foreign key and ModelPool has a hospital foreign key and AnnotationModel ManyToMany Field. Can we implement this using any other techniques exact error python3 manage.py migrate Operations to perform: Apply all migrations: admin, annotator, auth, contenttypes, sessions Running migrations: This version of djongo does not support "NULL, NOT NULL column validation check" fully. Visit https://nesdis.github.io/djongo/support/ Applying contenttypes.0001_initial...This version of djongo does not support "schema validation using CONSTRAINT" fully. Visit https://nesdis.github.io/djongo/support/ OK Applying contenttypes.0002_remove_content_type_name...This version of djongo does not support "COLUMN DROP NOT NULL " fully. Visit https://nesdis.github.io/djongo/support/ This version of djongo does not support "DROP CASCADE" fully. Visit https://nesdis.github.io/djongo/support/ OK Applying auth.0001_initial...This version of djongo does … -
Fetching rows by pairs of two column values in django
I have a table X like: +----+------------+-------+---------+ | id | product_id | name | deleted | +----+------------+-------+---------+ | 1 | 1 | "foo" | false | | 2 | 1 | "bar" | true | | 3 | 1 | "foo" | true | | 4 | 2 | "baz" | false | | 5 | 2 | "baz" | true | +----+------------+-------+---------+ the django model is: class X(models.Model): id = models.IntegerField() product_id = models.IntegerField() name = models.TextField(choices=get_choices()) deleted = models.BooleanField(default=False) given pairs of product with name I want to mark them as deleted. I have tried to create a list of concatenaded strings like product_names = ["foo1", baz2"] and then annotate with the query: queryset = X.objects.annotate( product_id_name=Concat("name", "product_id"), output_field=CharField(), ) if queryset.exists(): queryset.filter(deleted=False).filter( product_id_name__in=product_names ).update(deleted=True) But I am getting the error: QuerySet.annotate() received non-expression(s) -
ModuleNotFoundError: No module named 'django_plotly_dash'
I am creating a web application using django_plotly_dash, a module combining Django, Plotly, and Dash into one package. I am running into an issue where when I try to work with the manage.py file to run commands, I get the error ModuleNotFoundError: No module named 'django_plotly_dash' From research and the traceback, it seems to problem lies either in my settings.py file specifically with static files/bootstrapping or in my directory structure. Does anybody with more experience with this see any issues in my structures or settings.py that are causing this error Here is the Traceback message: Traceback (most recent call last): File "C:\Users\mvela\Documents\Internships\Contracts\Greene\July Contract\web_app\report_app\manage.py", line 22, in <module> main() File "C:\Users\mvela\Documents\Internships\Contracts\Greene\July Contract\web_app\report_app\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\mvela\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() File "C:\Users\mvela\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\django\core\management\__init__.py", line 395, in execute django.setup() File "C:\Users\mvela\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\mvela\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\Users\mvela\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\django\apps\config.py", line 212, in create mod = import_module(mod_path) File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.2032.0_x64__qbz5n2kfra8p0\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 972, in _find_and_load_unlocked 228, in _call_with_frames_removed 228, in _call_with_frames_r File "<frozen importlib._bootstrap>", line 1030, in _gcd_import … -
How to uglify VueJS code if not using vue-cli or build tools?
I am using VueJS in a Python Flask app, where once a page is rendered, VueJS app takes control of the page, and some single page behavior is taken care of. However, entire VueJS code with all data, methods, computed, etc is visible in source code. Is there a way to uglify this? Note: I'm not using vue-cli or using any proper javascript build process. -
Django admin get_readonly_fields inconsistent behavior
I have the same request as this other thread, I'm using Django 3.2.8 For my project some fields in the Admin pages will have to become readonly based on the value of one boolean field of that same model object, so I applied the solution that was advised in the other thread above. class OrdineAdmin(admin.ModelAdmin): inlines = [ FatturaAdmin ] readonly_fields = ["data"] def get_readonly_fields(self, request, obj=None): if obj and obj.pagato == True: self.readonly_fields = ['utente', 'abbonamento', 'importo', 'giorni_attivi_abbonamento', 'data'] return self.readonly_fields as I was expecting, this solution would lead to some inconsistency in the admin panel because one instance of OrdineAdmin would be generated in memory but it wouldn't update on each request. So when I set the field "pagato" to True this method does set all the other fields to readonly as expected but won't reverse its effect if I set that field back to False, even if the saving process through the admin panel succeeds. That is why I was thinking that something needed to be done inside the __init__() method but I read the answer to this other thread where in relation to inline admin elements it is said that it wouldn't make sense, as opposed … -
How to properly handle request based on user's permissions Django
Using Django I have a class based view to get a list of items from my database. Thing is that this list should not be accessible to every user. A user that does not have admin or is_staff privileges should be able to see all items, whereas a regular account without this privilege will have access only to their items. I was wondering how I should implement this. Have a class based view where I check if the user is an admin and if so get all items back. And have another class based view that checks if the user is not an admin and gets all items back for only that user. or Have one class based view where I check if the user is admin and not admin and that one class based view handles the request differently depending on the 2 different scenarios. I'm not sure what the "Django way" is but I would naturally go with the 2nd approach but thought I'd ask just in case. -
Django Logging Root Logger Not Getting Log Messages from Part of my Project
i have configured my dictconfig as follows, and i expected that all log records generated in the various part of my application would be propagated to the root logger, but the case is the opposite as no log records are recieved or logged by the root logger. Please can effect be explained and also can the working of the root logger be explained. LOGGING = { "version": 1, "disable_exisiting_loggers": False, 'formatters': { ... }, 'filters': { ... }, "handlers": { 'file' : { 'level': 'DEBUG', 'class' : 'logging.FileHandler', 'filename' : 'general.log', 'formatter' : 'standard', }, 'research': { 'level': 'INFO', 'class': 'logging.FileHandler', 'filename' : 'research.log', 'formatter': 'standard', }, }, "loggers": { '' : { 'handlers' : ['research', 'file'], 'level' : 'INFO', }, }, } -
Clean previous data django
I have a JSONField in my model and I wasn't able to clean the initial import on my resource so the data imported were treated as strings instead of lists. When I export the data it looks like this: The ones below are the previous data from the initial import-export without a custom JSONWidget. The ones above are the data that was cleaned. How can I then fix the current JSONField with the string and convert it to a list? -
How to join two querysets from different model into one based on key field in Django?
Currently on Django/MySQL setup I need to join two queries from different models into one but unlike CHAIN or UNION, I need the final queryset's record set to expand to include data retrieved from both queries based on the common key (sales_date) as well as a SUM field. Please see below for better explanation of my question: querysetA: | id | sales_date | store_sales| |----+------------+------------| | 1 | 2020-01-15 | 2000.00 | | 2 | 2020-01-16 | 1000.00 | | 3 | 2020-01-17 | 3000.00 | |------------------------------| querysetB: | id | sales_date |online_sales| |----+------------+------------| | 1 | 2020-01-15 | 1500.00 | | 2 | 2020-01-16 | 800.00 | | 3 | 2020-01-17 | 2800.00 | |------------------------------| Joined querysetC from querysetA and B (my target result querysetC): | id | sales_date | store_sales|online_sales|combine_sales| |----+------------+------------+------------+-------------| | 1 | 2020-01-15 | 2000.00 | 1500.00 | 3500.00 | | 2 | 2020-01-16 | 1000.00 | 800.00 | 1800.00 | | 3 | 2020-01-17 | 3000.00 | 2800.00 | 5800.00 | |---------------------------------------------------------| My code for both querysets as below querysetA = store_shop.objects.filter( sales_date__range=(fromdate, todate)) \ .values('sales_date') \ .annotate(store_sales=Sum('sales_income')) \ .order_by('sales_date') querysetB = online_shop.objects.filter( sales_date__range=(fromdate, todate)) \ .values('sales_date') \ .annotate(online_sales=Sum('sales_income')) \ .order_by('sales_date') Both union() and itertools.chain … -
View not rendering in % includes
Using Django I have a basic view that renders some data from the database. When I pass the view into my page {% include 'pages/games_table.html' %} the data is not being passed in. But if I go directly to the view I can see the data. view.py @login_required def showGame(request): results=Game.objects.all() return render(request,"pages/games_table.html",{"Game":results}) class Meta: db_table="apps_game" Direct to view i get this: but when i view within my template or i get is a blank table I think i have past data correctly so not sure what i am missing? Thanks -
Python Django jquery
Before in my models.py I had report_division = models.TextField(blank=True, max_length=40) and I counted by filter using this line in my views.py: CRS = Post.objects.filter(report_division='Something').count() Now I have a seperate class in my models.py class Divizija(models.Model): naziv_divizija = models.CharField(max_length=40) def __str__(self): return self.naziv_divizija class Post(models.Model): report_division = models.ForeignKey(Divizija, on_delete=models.SET_NULL, null=True, verbose_name="Divizija") I can't get my query to work now. I tried: CRS = Post.objects.filter(report_division=1).count() CRS = Post.objects.filter(report_division_id=1).count() CRS = Post.objects.filter(report_division='Something').count() -
With the bpython shell, how do I preload imports when the shell starts up?
I'm using Django 3.2, Python 3.9 and bpython==0.21 for a more useable shell. However, I notice when I start using my shell, I always have to run the same import commands $ python manage.py shell >>> from cbapp.models import * >>> from cbapp.services import * I like the bpython shell and would prefer to continue to use it, but is there a way that the imports can be run prior to the shell loading so I don't have to type (or scroll to) them each time? -
How to implement ADFS SSO having Django as backend and React as frontend?
I have registered a app for the django application in Azure Active directory. After the configuration of ADFS to Django app the SSO is working fine. Now I have integrated this Django app with a React app. Now I gotta implement SSO for the same. I need some guidance and direction on how to go forward with this. Please give me an idea to work on this. -
Django Template - How to check if dynamically constructed key has value in Object
I've an object that contains names like draft = { "name_ar": "test arabic", "name_en": "test english", "name_tr": "test turkish", "name_nl": "", } and I've language_code variable which will have either 'ar' or 'en' values. So before checking if key has value in the object what I did is I constructed the key first like below {% with name='name_'|add:language_code %} So now my query is I want to add class grey-color to div container if name doesn't have value in draft object. How can I achieve this? {% with name='name_'|add:language_code %} <span class="secondary-title {% if not "how can I check here" %}grey-color{% endif %}"> {% endif %} I'm very new to Django so happy to hear any suggestions or solution. -
Django template html variable inside a variable
In my views i created a variable passing in the context that looks like this {13: {112: 33.333333333333336, 120: 66.66666666666667, 125: 66.66666666666667}, 14: {110: 20.0, 111: 20.0, 113: 20.0, 121: 40.0, 126: 40.0}} In my template i am inside a loop from questions, and want to assign this values to answers inside the question: {% for question in questions %} <div class="ui basic padded segment left aligned"> <h4 class="ui header"> Question {{ forloop.counter }} / {{ questions|length }}: {{ question.prompt }} </h4> <ul> {% for option in question.answer_set.all %} <li> {{ forloop.counter }}) {{option.text}}: {{ ans.{{ question.pk }}.{{ option.pk }} }} %. {{ ans.13.120 }} </li> {% endfor %} </ul> </div> {% endfor %} If I use {{ ans.13.120 }} it works, but is not dynamic.... I want a way to use variables inside the {{ }}... something like: {{ ans.(question.pk).(option.pk) }}... Is it possible? -
Why blocks are not displayed on the page?
I ran into such a problem, the blocks do not want to be displayed on the page, which I do not really understand, since I did not work with the template engine before. this is code views.py class IndexView(generic.ListView): template_name = 'Homepage/index.html' model = Goods context_object_name = 'goods' def sale(request): return render(request, 'Homepage/sale.html') This is code of index.html <td>{% block sale %} {% endblock %}</td> This is code of sale.html {% extends "index.html" %} {% block sale %} <td class ="sale"> <img src="image"> <h1 class="description">description</h1> <a class="buy" href="#openModal" > <span >Купить</span></a> <h1 class="price">цена</h1> </td> {% endblock %} And this is the construction of the template -
Django + Celery + Redis on a K8s cluster
I have a Django application deployed on a K8s cluster. I need to send some emails (some are scheduled, others should be sent asynchronously), and the idea was to delegate those emails to Celery. So I set up a Redis server (with Sentinel) on the cluster, and deployed an instance for a Celery worker and another for Celery beat. The k8s object used to deploy the Celery worker is pretty similar to the one used for the Django application. The main difference is the command introduced on the celery worker: ['celery', '-A', 'saleor', 'worker', '-l', 'INFO'] Scheduled emails are sent with no problem (celery worker and celery beat don't have any problems connecting to the Redis server). However, the asynchronous emails - "delegated" by the Django application - are not sent because it is not possible to connect to the Redis server (ERROR celery.backends.redis Connection to Redis lost: Retry (1/20) in 1.00 second. [PID:7:uWSGIWorker1Core0]) Error 1: socket.gaierror: [Errno -5] No address associated with hostname Error 2: redis.exceptions.ConnectionError: Error -5 connecting to redis:6379. No address associated with hostname. The Redis server, Celery worker, and Celery beat are in a "redis" namespace, while the other things, including the Django app, are in …