Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Should I list the contestants according to the selected division?
I'm new to web development and I use the Django framework! I ask you to help or guide me on the right path. It is necessary to implement a selection of contestants according to the division selected from the drop-down list. The contestant model has a secondary key to the division model, the template implements the output of two forms: class divisionForm(ModelForm): # Подразделения class Meta: model = division fields = ['name_division'] widgets = { "name_division": Select(attrs={}), } class contestantForm(ModelForm): # Конкурсанты class Meta: model = contestant fields = ['name_contestant'] widgets = { "name_contestant": Select(attrs={}), } enter image description here As far as I understand, Django acts as a server and when the page loads, it returns the data processed in views.py how to implement the withdrawal of all contestants from the selected division in the template? already on the client side without POST and GET requests. Do you have a javascript example for interacting with Django on a similar topic? -
Concatenate 2 RawQuerySets Django
so i have each entity their and they are from legacy system, thats why i cannot perform migration. For example : Entity1 Blog Entity1 Entry Entity2 Blog Entity2 Entry There are 9 entities, means 18 tables So here is my view.py but i cannot do entity1_data.union(entity2_data). How can i merge these, so i can present it in 1 table? Ps: i would try union SQL, but theres too long. entity1_data = BlogModel.objects.using("bcdb").raw("SELECT blog.id as id, blog.name," + "entry.title, " + "entry.date " + "FROM [Entity1 Blog] as blog " + "INNER JOIN [Entity1 Entry] as entry " + "on blog.id = entry.blog_id") entity2_data = BlogModel.objects.using("bcdb").raw("SELECT blog.id as id, blog.name," + "entry.title, " + "entry.date " + "FROM [Entity2 Blog] as blog " + "INNER JOIN [Entity2 Entry] as entry " + "on blog.id = entry.blog_id") I hope i can do it dynamically using dict of tables name. Merged table | Blog ID | Blog Name | Entry Title | Entry Date | | ------------------ | -------------------- | ---------------------- | --------------------- | | [Entity 1 Blog].ID | [Entity 1 Blog].name | [Entity 1 Entry].title | [Entity 1 Entry].date | | [Entity 2 Blog].ID | [Entity 2 Blog].name | [Entity 2 Entry].title … -
Question about using Group or Role in frontend application to restrict view
I am building an application that comprises a python backend using the django framework and a vue application on the frontend. I am using with success the authorization and permissions framework provided by django. I have created groups that possess a set of permissions and I have assigned users to them. Technically, after reading the docs, it is recommended to use groups to check for permissions and not roles. A problem arises when I need to serialize the user and send it to the frontend. What kind of information should I send to determine permissions on the frontend? Should I serialize all the groups the user belongs to with the respective permissions, or should I create a role field in my database to simplify things out (the roles are quite well defined) and just send that. What is the common solution or what would be reasonable? What kind of questions should be answered when approaching this problem? Thank you for your time. -
while we want to develop a travelling website using react how can we integrate a map api into our project
we need to provide a route map just like the google maps based on the user input that he/she wanted to visit the place, that should display the starting and destination locations of the user along with the type of transport that is available to visit that place. we tried to integrate the google maps API by generating a token but we are unable to integrate it in our project and we suppose that it is also not free of cost.so we need a map API and the process to integrate the API that can take the user input(location that the user wanted to visit). -
Django Project on Heroku
-----> Building on the Heroku-22 stack -----> Using buildpack: heroku/python -----> App not compatible with buildpack: https://buildpack-registry.s3.amazonaws.com/buildpacks/heroku/python.tgz More info: https://devcenter.heroku.com/articles/buildpacks#detection-failure ! Push failed I have tried to setup a buildpack. Heroku/Python, but yet the error have refused to go. Pls how can i fix this? -
cannot call recv while another coroutine is already waiting for the next message
RuntimeError: cannot call recv while another coroutine is already waiting for the next message hello I wrote a counsumer that acts as a middleware that connects to the server socket, for example X, then receives the data and adds a series of information to the data, then sends it to the clients connected to the consumer. When the first client connects it works fine and when the second client connects it gives the following error: RuntimeError: cannot call recv while another coroutine is already waiting for the next message class ConnectionManager: connection = None connection_lock = asyncio.Lock() @classmethod async def get_connection(cls): async with cls.connection_lock: if cls.connection is None or not cls.connection.open: cls.connection = await cls.create_connection() return cls.connection @classmethod async def create_connection(cls): email = "email" password = "Password" url = "url" session = requests.Session() params = urlencode({"email": email, "password": password}) headers = { "content-type": "application/x-www-form-urlencoded", "accept": "application/json", } session.post(url + "/api/session", data=params, headers=headers) cookies = session.cookies.get_dict() token = cookies["JSESSIONID"] return await websockets.connect( "ws://url", ping_interval=None, extra_headers=(("Cookie", "JSESSIONID=" + token),), ) class WebsocketConsumer(AsyncWebsocketConsumer): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.message_queue = asyncio.Queue() async def connect(self): await self.accept() await self.channel_layer.group_add("group", self.channel_name) asyncio.ensure_future(self.handle_connection()) async def disconnect(self, close_code): await self.channel_layer.group_discard("group", self.channel_name) async def receive(self, text_data): pass … -
Can't add some native django cms plugins in my pages
I am getting the problem of not being able to add some native django cms plugins in my templates. i keep getting the message Please correct the error below. i tried to debug it but i am new to django and i can't see where i went wrong. Can it be a problem with django cms it self? with no errors showing in the form. the errror This is my settings.py from pathlib import Path import os import dj_database_url from django_storage_url import dsn_configured_storage_class from django.utils.translation import gettext_lazy as _ gettext = lambda s: s # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = os.environ.get('SECRET_KEY', '<a string of random characters>') # SECURITY WARNING: don't run with debug turned on in production! DEBUG = os.environ.get('DEBUG') == "True" ALLOWED_HOSTS = [os.environ.get('DOMAIN'),] if DEBUG: ALLOWED_HOSTS = ["*",] # Redirect to HTTPS by default, unless explicitly disabled SECURE_SSL_REDIRECT = os.environ.get('SECURE_SSL_REDIRECT') != "False" X_FRAME_OPTIONS = 'SAMEORIGIN' LOGGING = { "version": 1, "disable_existing_loggers": False, "handlers": { "file": { "level": "ERROR", "class": "logging.FileHandler", "filename": "/debug.log", }, "console": { "class": "logging.StreamHandler", }, }, "loggers": { "django": { "handlers": ["file", "console"], "level": … -
django-celery-worker add delay task
my django project, use celery and sent delay task, but callback delay task raise django.db.utils.InterfaceError: (0, '') my code: @celery_app.task def delayTaskTest22222222222222222(index): """ """ print(index) import time time.sleep(15) @celery_app.task def error_handler(request, exc, traceback): # print('Task {0} raised exception: {1!r}\n{2!r}'.format( # request.id, exc, traceback)) # print() from cmdb.models import MyModel aa = MyModel.objects.all().count() print(aa) @celery_app.task def delayTaskEntry(): """""" print('-' * 50) delayTaskTest22222222222222222.apply_async(args=(11111,), time_limit=5, link_error=error_handler.s()) I exec delayTaskEntry method, and celery raise Error: File "/home/my/.pyenv/versions/3.8.8/envs/abc/lib/python3.8/site-packages/pymysql/cursors.py", line 148, in execute result = self._query(query) File "/home/my/.pyenv/versions/3.8.8/envs/abc/lib/python3.8/site-packages/pymysql/cursors.py", line 310, in _query conn.query(q) File "/home/my/.pyenv/versions/3.8.8/envs/abc/lib/python3.8/site-packages/pymysql/connections.py", line 547, in query self._execute_command(COMMAND.COM_QUERY, sql) File "/home/my/.pyenv/versions/3.8.8/envs/abc/lib/python3.8/site-packages/pymysql/connections.py", line 793, in _execute_command raise err.InterfaceError(0, "") django.db.utils.InterfaceError: (0, '') I want set delay task time_limit and get all Error, what should i modify my code. Think you!!!!! -
On-Tick Callback Not Executing in Python Virtual Environment
On-Tick Callback Not Executing in Python Virtual Environment but working in local Environment what was the issue. class Command(BaseCommand): def handle(self, *args: Any, **options: Any): api_key = "" api_secret = "" session_token = "" print("Connecting to Breeze") breeze = BreezeConnect(api_key="") print("WebSocket connected successfully") breeze.generate_session(api_secret="", session_token="") breeze.ws_connect() print("WebSocket connected successfully") def on_ticks(ticks): print("Ticks: {}".format(ticks)) breeze.on_ticks = on_ticks breeze.subscribe_feeds(exchange_code="NFO", stock_code="ADAENT", product_type="options", expiry_date="28-Dec-2023", strike_price="3000", right="Call", get_exchange_quotes=True, get_market_depth=False) print("Subscribed to ADAENT options") breeze.ws_disconnect() print("Disconnected from WebSocket") I have a Django management command located in the management/commands folder. When I run this file using python3 manage.py file_name in my virtual environment, the on_ticks callback function is not getting called, and no data is printed. However, the code works fine in my local environment. The virtual environment is active during the file execution, and all required packages are installed. What could be causing the on_ticks function not to execute in the virtual environment? When i run this script in virtual environment the on_ticks callback function is called and print the on_ticks Data. -
How do I efficiently evaluate and exclude certain values from a Django queryset?
I have a model where I have 4 datetime fields (last_fed is gotten from user input, the others are generated at form creation, not added here for brevity). class EatModel(models.Model): user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) medicine = models.ForeignKey(MedicalInfo, on_delete=models.SET_NULL, null=True) interval = models.IntegerField(default=4) last_fed = models.DateTimeField(default=datetime.now) second_dose = models.DateTimeField(default=None, null=True) third_dose = models.DateTimeField(default=None, null=True) fourth_dose = models.DateTimeField(default=None, null=True) fifth_dose = models.DateTimeField(default=None, null=True) remarks = models.TextField(max_length=140, blank=True) complete = models.BooleanField(default=False) created = models.DateTimeField(auto_now_add=True) I have a generic TemplateView display to output the results to show the various doses. class newlist(LoginRequiredMixin, TemplateView): template_name = 'trackerapp/eatmodel_newlist.html' login_url = 'eatlogin' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['list'] = EatModel.objects.filter(user=self.request.user) return context I want to improve the view so that instead of just displaying all datefields into the template, I want to evaluate if each of them is lesser than localtime() and if so, I want to exclude specifically those values from the queryset (so if we're past the datetime for second dose, it just passes to context third_dose and fourth_dose) I experimented quite a bit with filter, exclude, defer, Q but couldn't get it to still return the row (less unwanted values). One way that I thought could work was to split it into … -
Show 'is_staff' as False in Django template
I am writing a front end admin portal to allow for admins to manage users from a front end perspective. I am trying to get a 'user status' table set up so that admins can get the users current status. I am using the is_staff and is_active within the auth_users table to get the users status. I have tried several ways but for some reason I cannot get is_staff = false to work. Here is my current code. template.py Please note these are two seperate ways and examples of the goal I am trying to get <table class="table table-striped"> <thead> <tr> <th>User</th> <th>Status</th> <th>Title</th> </tr> </thead> <tbody> {% for active_users in active_users %} <tr> <td >{{active_users}}</td> <td> {% if user.is_active %} Active {% else %} Not Active {% endif %} </td> <td> {{get_status}} </td> <td> <a class="btn btn-primary" href="/manage_user/{{active_users.id}}"><i class="bi bi-person-add"></i> Manage User</a> </td> </tr> {% endfor %} </tbody> </table> For the is_active, I tried using the tags and filters. <td> {% if user.is_active %} Active {% else %} Not Active {% endif %} </td> I also tried: <td> {% if user.is_active %} Active {% elif user.is_active == False%} Not Active {% endif %} </td> I tried those two options … -
I have a problem merging navigation bar and footer html file together in my base html
I've been trying to figure out how to include the two templates in my base html and I found no success. I'm not certainly familiar with {% include %} and {% extends %} function and I believe I am not using it correctly to fix problem. With that being said, I added my navigation bar html using {% include %} on my base html along with my footer html also using with {% include %} as shown. The result is only the footer html appeared meanwhile the navigation bar html only resulted to a horizontal line beneath the search bar. {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>home</title> <link rel="stylesheet" href="/static/css/homestyle.css"> </head> <body> {% include 'webapp/templates/pages/navbar.html' %} <!-- navigation bar html --> {% include 'webapp/templates/pages/footer.html' %} <!-- footer html--> </body> </html> <!--navigation bar html --> {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>navbar</title> <link rel="stylesheet" href="/static/css/navbar.css">` ` </head> <body> <nav class="login_nav"> <p> login </p> </nav> <hr class="solid"> <nav> <img src="/static/images/user_logo.png"> <ul class="nav_links"> <li><a href="http://127.0.0.1:8000/artists/"> apple </a></li> <li><a href="http://127.0.0.1:8000/gallery/"> banana </a></li> <li><a href="http://127.0.0.1:8000/about/"> grape </a></li> </ul> </nav> <hr class="solid"> </body> </html> [`<!--footer html --> {% load static %} <!DOCTYPE html> <html lang="en"> <head> … -
How to combine selection and assignment in a single Django ORM query?
I'm trying to avoid race conditions when assigning objects from a pool to another object. meerkat_pool = Meerkat.objects.filter(customer=None) customer.meerkat = meerkat_pool.first() customer.save() Simultaneous requests result in the same meerkat being assigned to two different customers. Is there a way to run this as a single database query? F() expressions would be ideal if I could transform the QuerySet to a single value (e.g. customer.meerkat = F("first_meerkat_in_pool")). -
how to get the profile of a user we click on?
I made this blog and I want to when click on a user's profile from any post the website goes to that specific use's profile I mean the one who wrote the post but right now I can only get the profile picture of the current logged in user what should I do? if I need to post more code please let me know Thanks in advance my profile page {% extends "base.html" %} {% load static %} {% block content %} <div class="frame"> <div class="center"> <div class="profile"> <div class="image"> <div class="circle-1"></div> <div class="circle-2"></div> <img src="{{ post.author.profile.image.url }}" width="70" height="70"> </div> <div class="name">{{ post.author }}</div> <div class="job">Visual Artist</div> <div class="actions"> <button class="btn">Follow</button> <button class="btn">Message</button> </div> </div> <div class="stats"> <div class="box"> <span class="value">523</span> <span class="parameter">Posts</span> </div> <div class="box"> <span class="value">1387</span> <span class="parameter">Likes</span> </div> <div class="box"> <span class="value">146</span> <span class="parameter">Follower</span> </div> </div> </div> </div> {% endblock %} -
Django set up api
I want to use django as backend to create an api that can pass to Frontend, so i just created the api but it cant work, i just want testing in Insomnia but it always cant find the urls, but i have write the path. I need to use the JSONView so i can test the api in Insomnia, someone help to see where i wrong in the path This is my whole code in app views.py import ret from django.shortcuts import render from django.http import HttpResponse from . import models from django.http import JsonResponse from json import JSONDecodeError # Create your views here. class JSONView: def dispatch(self, request, *args, **kwargs): try: input_data = self.parse_input_data(request) ret = {'success': False} return super().dispatch(request, input_data=input_data, ret=ret, *args, **kwargs) except JSONDecodeError: return JsonResponse({'success': False, 'error': 'Invalid JSON data'}) def parse_input_data(self, request): pass class ProductView(JSONView): def post_product_list(self, request, input_data, ret): product = models.Product.objects.values() ret['success'] = True ret['product'] = product @classmethod def as_view(cls): pass This is my whole code in app urls from django.contrib import admin from django.urls import path from . import views urlpatterns = [ path('admin/', admin.site.urls), path('api/Product/product_list/', views.ProductView.as_view(), name='product_list'), ] This is my whole code in project urls """ URL configuration for jqe_shop … -
django-auditlog: traversing relationships to get LogEntries of related objects
For tracking changes, I've created a mixin to add auditlog to model components to make tracking change uniform. It's paying dividends when it's time to generate reports about what's changed. class ChangeMixin: history = AuditlogHistoryField() def get_all_changes(self, range_start=DAY_START, range_end=DAY_END): """ returns all the changes on this instance within a defined time period. The default period is today. :type range_end: datetime :type range_start: datetime """ result = [] if range_start > range_end: return result if self.history is None: return result result = LogEntry.objects.get_for_object(self).filter(timestamp__range=(range_start, range_end)) return result However, there's a fly in the ointment that this solution doesn't address: how to get the corresponding bits from related objects. That is, if there is a one to many or a many to many relationship, how do pursue the relationship to get the target data? For example, if there's a one to many relationship, say Book to Genre, the LogEntry stores the id of the Genre in the change record and the hope is get the text version of the record whose id is in the LogEntry. That is, the genre for a book, say the Hobbit, might get changed from fiction to fantasy. The LogEntry record for the Hobbit might show this as … -
How do I pass dynamic values to Django urls to avoid NoReverseMatch at error
I am trying to build a hotel reservation app with Django, but I am having trouble passing the data through the app. I continue to get this error NoReverseMatch at /search_results/ Reverse for 'more_info_page' with keyword arguments '{'room_type': 'double', 'check_in_date': '2023-12-07', 'checkout_date': '2023-12-09', 'guests': '1'}' not found. 1 pattern(s) tried: ['more_info_page/(?P<room_type>[^/]+)/(?P<check_in_date>[^/]+)/(?P<check_out_date>[^/]+)/(?P[^/]+)/\Z'] I cannot understand how I should pass these to the URL. Here is the HTML line causing the problems <a href="{% url 'more_info_page' room_type=room_type check_in_date=checkin_date checkout_date=checkout_date guests=guests %}" class="btn btn-primary">More Info</a> Here is my search_results view def search_results(request): if request.method == 'POST': checkin_date = request.POST.get('checkinDate') checkout_date = request.POST.get('checkoutDate') guests = request.POST.get('guests') check_in_date = datetime.strptime(checkin_date, '%Y-%m-%d').date() check_out_date = datetime.strptime(checkout_date, '%Y-%m-%d').date() available_rooms = Room.objects.filter(available=True) booked_rooms = Reservation.objects.filter( check_in_date__lte=check_out_date, check_out_date__gt=check_in_date ).values_list('room_id', flat=True) available_rooms = available_rooms.exclude(id__in=booked_rooms) available_room_types = available_rooms.values_list('type', flat=True).distinct() context = { 'checkin_date': checkin_date, 'checkout_date': checkout_date, 'guests': guests, 'available_room_types': available_room_types, } return render(request, 'results.html', context) else: return HttpResponse("Method not allowed") Here is my URL pattern path('more_info_page/<str:room_type>/<str:check_in_date>/<str:check_out_date>/<str:guests>/', views.more_info_page, name='more_info_page'), I have tried various permutations of passing the context, but I continue to get this reverse error. -
Potential Recommendations for a Computer Science Bachelor's Degree final project
I have a friend who will be finishing his Computer Science bachelor's degree next semestre, and he's trying to think what he could do for his final project. He plans to use Python as his main language, with potential frameworks like Kivy and/or Django. He's also considering using real data from his university if given permission for his project. So far he hasn't gotten any luck comming up with project ideas that can apply something computer science related such as AI or simulation. He also needs to make sure that it isn't exclusively an information system project (like if the project is just a simple dashboard or a normal website that won't do much). If anyone can offer any recommendations for what could be a good computer science final project for my friend i'd be very grateful. -
OperationalError: could not translate host name "db" to address: Name or service not known
I am using django on a project and we are switching from sqlite3 to postgres so we need to add postgres to docker. For some reason the webservice wont connect to postgres. Here is my docker-compose and settings. services: db: image: postgres:latest restart: always container_name: db environment: - POSTGRES_USER=pipeline_user - POSTGRES_PASSWORD=password - POSTGRES_DB=pipeline_service ports: - "5432:5432" networks: - django webservice: build: context: ./webservice dockerfile: WebService.Dockerfile command: python ./src/manage.py runserver 0.0.0.0:8000 ports: - "8000:8000" depends_on: - db networks: - django links: - db:db djangoq: build: context: ./webservice dockerfile: WebService.Dockerfile command: python ./src/manage.py qcluster ports: - "8001:8000" depends_on: - db networks: - django links: - db:db ui: build: context: ./ui dockerfile: UI.Dockerfile ports: - "4200:80" depends_on: - webservice networks: django: driver: bridge DATABASES = { # 'default': { # 'ENGINE': 'django.db.backends.sqlite3', # 'NAME': 'pipeline_service.sqlite3', # } 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'pipeline_service', 'USER': 'pipeline_user', 'PASSWORD': 'password', 'HOST':'db', 'PORT':'5432' } } Can anyone see what I'm missing? I have found several other people with this issue and most of the solutions were adding networks to the docker-compose.yml file or setting the container_name for postgres, but those haven't worked for me. -
static files for django admin can't be found while running asgi server
Here is my settings.py # ...other settings STATIC_ROOT = os.path.join(BASE_DIR, "static") STATIC_URL = 'static/' # ...other settings Then I run python manage.py collectstatic uvicorn Django_Channels.asgi:application --port 8000 --workers 4 --log-level debug --reload this collects static (after that I do have static folder at the root folder), starts the asgi server, but when I go to the admin page it looks like without any CSS or JS files. Just a bunch of unorganised text. Here are the logs from terminal: Here what logs look likeINFO: 127.0.0.1:51770 - "GET /static/admin/css/dashboard.css HTTP/1.1" 404 Not Found Not Found: /static/admin/css/responsive.css INFO: 127.0.0.1:51770 - "GET /static/admin/css/responsive.css HTTP/1.1" 404 Not Found Not Found: /static/admin/js/theme.js INFO: 127.0.0.1:51769 - "GET /static/admin/js/theme.js HTTP/1.1" 404 Not Found Not Found: /static/admin/js/nav_sidebar.js INFO: 127.0.0.1:51770 - "GET /static/admin/js/nav_sidebar.js HTTP/1.1" 404 Not Found I am always having a bad time with staticfiles, could please somebody tell me what am I doing wrong? -
Why am I getting a CSRF Token Verification Error when submitting a post request using Django?
I have a simple form to send an email to my personal email. I'm able to send the email fine in the development environment, but in the production environment (I use Heroku and the Mailgun addon for hosting and Cloudflare for my domain) I get a 403 Forbidden Error. Heroku provides my SSL certificate for my site. I checked my middleware is in the correct order, and I have my production environment settings as follows: DEBUG = False SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') SESSION_COOKIE_SECURE = True CSRF_COOKIE_SECURE = True ALLOWED_HOSTS = [ 'anonymousdomain.com', 'www.anonymousdomain.com', 'pointer1.herokudns.com', 'pointer2.herokudns.com'] DATABASES = { 'default': dj_database_url.config() } EMAIL_HOST = os.environ.get('MAILGUN_SMTP_SERVER', '') EMAIL_PORT = os.environ.get('MAILGUN_SMTP_PORT', '') EMAIL_HOST_USER = os.environ.get('MAILGUN_SMTP_LOGIN', '') EMAIL_HOST_PASSWORD = os.environ.get('MAILGUN_SMTP_PASSWORD', '') I checked the headers when making the request and the origin is the same as the referrer except the referrer has a trailing slash at the end of the domain but I don't think that should be an issue (e.g. the origin is https://www.anonymousdomain.com and referrer is https://www.anonymousdomain.com/). My allowed hosts is allowing all the domains and domain pointers that I use in my DNS (the one's given by Heroku when you add a custom domain) as well. The only thing I can … -
Change Django rest framework Response Class
This is my first question here I want to change the default Response classe for Django rest framework, I've found this article https://dextrop.medium.com/creating-a-custom-response-class-for-django-rest-framework-4c1a9a65561b But it doesn't seem that DEFAULT_RESPONSE-CLASS is supported by DRF settings Any idea ? Thank you very much -
django-fsm FSMKeyField transition identifier
I'm currently facing an issue while trying to define a transition identifier using the 'type' field of a ForeignKey model in Django. After carefully reading the documentation, I noticed that the examples provided primarily utilize the primary key for transition identifiers. Here are some examples: Test examples I'm wondering if anyone has experience or insights into how to specify a transition identifier using the 'type' field of a ForeignKey. Any guidance or examples demonstrating the correct approach in such scenarios would be greatly appreciated. Thank you! class Stage(models.Model): class Type(models.TextChoices): SUBSCRIBED = ( "SUBSCRIBED", _("Subscribed"), ) SELECTED = ( "SELECTED", _("Selected"), ) APPROVED = ( "APPROVED", _("Approved"), ) name = models.CharField(max_length=255) type = models.CharField( max_length=255, choices=Type.choices, default=Type.CUSTOM, ) class Recruitment(models.Model): class Status(models.TextChoices): ACTIVE = ("ACTIVE", _("Active")) INACTIVE = ("INACTIVE", _("Inactive")) stage = FSMKeyField(Stage, on_delete=models.RESTRICT, protected=True) @transition( field=stage, source=[Stage.Type.SUBSCRIBED], #This not works target=Stage.Type.SELECTED, ) def select(self, description=None, by=None): return "Candidate was selected!" I want to discover a way to implement a feature. -
Is it possible to filter Django objects by a list of dictionaries?
Let's say I have a queryset of django objects i.e. Blog with fields id, hits, title and also a list of dictionaries which represent those objects: blog_list = [{'id': 1, 'hits': 30, 'title': 'cat'}, {'id': 2, 'hits': 50, 'title': 'dog'}, {'id': 3, 'hits': 30, 'title': 'cow'}] One of the django object has a value different from one specified in the list of dictionaries. For example, I have a blog instance with id = 1, hits = 30, but title = 'new cat' Right now I do: for blog in queryset: for entry in blog_list: if blog.id == entry['id'] and blog.title != entry['title']: print(f'It is the blog entry with id {blog.id}') But it looks suboptimal and too complicated. Is there a smart way to find such object? -
Scalingo : serving static files for Django ASGI
I've been trying to deploy a Django ASGI app on Scalingo for a few days, and I can't manage to serve the static files. When I load the app I get a 404 on the css file. My Procfile contains only this line : web: gunicorn gingembre.asgi --worker-class=uvicorn.workers.UvicornWorker --log-file - And if I run this command locally, it works, static files included. Following Scalingo documentation, my settings.py file contains the following lines : BASE_DIR = os.path.dirname(os.path.dirname(__file__)) STATIC_ROOT = 'staticfiles' STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) I've been tweeking these settings for a while now, and I don't know what to try. I read a lot about whitenoise, but it don't seems compatible with ASGI (this PR is not merged yet).