Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Celery and Redis error when running celery
I'm making a django app with celery and redis that udpates stock prices asynchronously. I'm working on the background tasks right now and celery won't run properly. I turn on the Redis server then django server and when I turn on the celery one with celery -A celery worker -l info I get this error... [2023-07-24 20:25:37,798: ERROR/MainProcess] consumer: Cannot connect to amqp://guest:**@127.0.0.1:5672//: [Errno 61] Connection refused. Trying again in 2.00 seconds... (1/100) There's also this above it and I want to point out that it's not connecting to my broker url I provided it.. [2023-07-24 20:25:37,688: WARNING/MainProcess] No hostname was supplied. Reverting to default 'localhost' celery@Gabes-MBP.hsd1.ca.comcast.net v5.3.1 (emerald-rush) macOS-13.2.1-arm64-arm-64bit 2023-07-24 20:25:37 [config] .> app: default:0x101ecc220 (.default.Loader) .> transport: amqp://guest:**@localhost:5672// .> results: disabled:// .> concurrency: 8 (prefork) .> task events: OFF (enable -E to monitor tasks in this worker) [queues] .> celery exchange=celery(direct) key=celery [tasks] This is my settings.py, #celery settings CELERY_BROKER_URL = "redis://localhost:6379" CELERY_ACCEPT_CONTENT = 'application.json' CELERY_RESULT_SERIALIZER = 'json' CELERY_TASK_SERIALIZER = 'json' CELERY_TIMEZONE = 'America/New_York' CELERY_RESULT_BACKEND = 'redis://localhost:6379' CELERY_BEAT_SCHEDULER = 'django_celery_beat.schedulers:DatabaseScheduler' This is my celery.py, from __future__ import absolute_import, unicode_literals import os from celery import Celery # from django.conf import settings # from celery.schedules import crontab os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings.\_base') app … -
Setting up a postgresql testing database for pytest suite for django project
I am relatively new to Python/Django and Pytest. I have a couple of methods that I would like to test that require changes to be made to my database. I have been utilizing fixtures to set up and tear down my database per session. However, my pytests want to keep using my original database, which defeats the purpose of having a test database (I am getting access denied anyway saying "I cannot access this database in Testing"). I believe this is due to my database router I have setup. I plan to have a database per app in the project, so my logic is "app_name == database_name". Below is what I have for my setup and teardown: import pytest import psycopg2 import os @pytest.fixture(scope='session') def postgresql_db(): # Set up the test database connection db_name = 'test_db' connection = psycopg2.connect( dbname=os.environ.get('POSTGRES_DB', 'postgres'), user=os.environ.get('POSTGRES_USER', 'postgres'), password=os.environ.get('POSTGRES_PASSWORD', ''), host=os.environ.get('POSTGRES_HOST', 'localhost'), port=os.environ.get('POSTGRES_PORT', '5432'), ) # Create the test database with connection.cursor() as cursor: cursor.execute(f"CREATE DATABASE {db_name};") yield connection # Close the connection and clean up the test database connection.close() with psycopg2.connect( dbname=os.environ.get('POSTGRES_DB', 'postgres'), user=os.environ.get('POSTGRES_USER', 'postgres'), password=os.environ.get('POSTGRES_PASSWORD', ''), host=os.environ.get('POSTGRES_HOST', 'localhost'), port=os.environ.get('POSTGRES_PORT', '5432'), ) as cleanup_connection: with cleanup_connection.cursor() as cursor: cursor.execute(f"DROP DATABASE IF EXISTS {db_name};") Am … -
bind(): Operation not supported [core/socket.c line 230]
I'm having a problem running django with uwsgi/nginx on docker. please what could be the issue?uwsgi error I'm not quite sure what the issue is and I've tried googling the error, but nothing comes up. bellow is my uwsgi and nginx set up. [uwsgi] socket=/code/educa/uwsgi_app.sock chdir= /code/educa/ module=educa.wsgi:application master=true chmod-socket=666 uid=www-data gid=www-data vacuum=true # upstream for uWSGI upstream uwsgi_app { server unix:/code/educa/uwsgi_app.sock; } server { listen 80; server_name www.educaproject.com educaproject.com; error_log stderr warn; access_log /dev/stdout main; location / { include /etc/nginx/uwsgi_params; uwsgi_pass uwsgi_app; } } -
Specifying filename when using boto3.upload_file()
I am using boto3.client('s3').upload_file(source_file_path, bucket, key) to upload a file I have generated. How do I specify a user friendly file name for this file when it is downloaded? -
Django: How do I serialize a nested relationship when the nested target has inherited subtypes?
How can I create a serializer for a nested relationship, with a transaction, where the nested relationship has several child types? I’ve read through the documentation and that doesn’t seem to be well-covered. We have an application for insuring homeowners, with the following structure: class Homeowner(models.Model): name = models.CharField(max_length = 100, null = True, blank = True) property = models.ForeignKey(Property, null = True) class Property(models.Model): address = models.CharField(max_length = 500, null = True, blank = True) # lots more removed. Not an abstract model. class House(Property): number_of_floors = models.IntegerField(default = 1) class Condo(Property): has_doorman = models.BooleanField(default = False) (This is strictly for show; the different home types have a lot of discount or liability fields.) For years, the way we’ve done this is that we’ve entered the property by hand, and then entered the homeowner as two separate stages, linking them with a search-for-properties dialog on the homeowner page. It’s always been a zero-or-one-to-one relationship: A property may have zero or one homeowners, and a homeowner may have zero-or-one properties. The orders have come down to create a unified experience that the homeowner can fill out themself: enter the whole thing, homeowner and property, and validate them together, rolling everything … -
Django allauth not able to login custom user, giving error asking to enter correct credentials--user exists in database
I having issues logging in a user with a custom user model with allauth. The user is in the database but is not able to login. I am able to login as admin but not as other testusers I get an error asking to enter the correct username and password--the username and password are correct and the user is active. models.py from django.db import models # Create your models here. from django.contrib.auth.models import AbstractUser, AbstractBaseUser class UserModel(AbstractUser): ACCOUNT_TYPE = ( ('account_type_a','Account Type A'), ('account_type_b','Account Type B'), ('account_type_c','Account Type C'), ) username = models.CharField(max_length=50) email = models.EmailField(max_length=50) account_type = models.CharField(choices=ACCOUNT_TYPE, max_length=50, null=True, blank=True) is_active = models.BooleanField(default=True) is_staff = models.BooleanField( default=False) I using the allauth login form like so: html <a class="nav-link" href="{% url 'account_login' %}">Login</a> settings.py AUTH_USER_MODEL = 'accounts.UserModel' AUTHENTICATION_BACKENDS = [ # Needed to login by username in Django admin, regardless of `allauth` 'django.contrib.auth.backends.ModelBackend', # `allauth` specific authentication methods, such as login by e-mail 'allauth.account.auth_backends.AuthenticationBackend', ] LOGIN_REDIRECT_URL = 'memberships:profile' LOGOUT_REDIRECT_URL = 'account_login' ACCOUNT_SIGNUP_PASSWORD_ENTER_TWICE = False ACCOUNT_USERNAME_REQUIRED = False # This removes the username field ACCOUNT_AUTHENTICATION_METHOD = 'email' ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_UNIQUE_EMAIL = True ACCOUNT_USER_MODEL_USERNAME_FIELD = None -
Django + Django Tenants + DRF API = http: error: gaierror: [Errno 11001] getaddrinfo failed
Can someone please help to resolve the error i am getting? I am using django-tenants package with DRF REST API The issue is that accessing API VIEW via browser works fine, for example: http://demo.localhost:9000/api/zakaz But sending requests to this address via "requests" gives the error: HTTPConnectionPool(host='demo.localhost', port=9000): Max retries exceeded with url: /api/zakaz/3/ (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x0000017E1D9FEB00>: Failed to establish a new connection: [Errno 11001] getaddrinfo failed')) Similarly and PING or HTTPIE request from console even to basic address "demo.localhost:9000" gives the same: http http://demo.localhost:9000/ http: error: gaierror: [Errno 11001] getaddrinfo failed Couldn’t resolve the given hostname. Please check the URL and try again. Meaning that this address is only resolved in browser, but not from Django or Python console.. What am i doing wrong? How do i send api request in django-tenants separately for each tenant? I have added rest framework to TENANT APPS: TENANT_APPS = ( # your tenant-specific apps 'rest_framework', 'api.apps.ApiConfig', 'orders.apps.OrdersConfig', 'patients.apps.PatientsConfig', ) -
Submit Button corrupting
I have a simple profil page and I want to change the profile picture. forms: class UserProfilePictureUpdateForm(forms.ModelForm): class Meta: model = UserProfile fields = ['profile_photo',] template: <form method="post" enctype="multipart/form-data" action='{% url "update_profil_photo" %}'> {% csrf_token %} <button class="btn btn-info" type="submit" value="{{ profile_form.profile_photo }}"> <i class="fa fa-fw fa-camera"></i> <span>Change Photo</span> </button> </form> views: @login_required def update_profil_photo(request): user_profile = get_object_or_404(UserProfile, user=request.user) user = request.user if request.method == 'POST': profile_form = UserProfilePictureUpdateForm(request.POST, request.FILES, instance=user_profile) if profile_form.is_valid(): profile_form.save() messages.success(request, 'Update is successful') else: profile_form = UserProfilePictureUpdateForm(instance=user_profile) return render(request, 'profile.html', {'profile_form': profile_form}) When I click the button the design corrupts. I see very big submit button, link of picture and file upload buttons. what's wrong with my approach -
I want to create a API endpoint to fetch User and User Profile by attribute "username" in djangoRestAPI, username will be sent by the client,
**model.py ** class User_profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) name = models.CharField(max_length=50, blank=False) phone = models.CharField(max_length=20, blank=False) profileImg = models.ImageField(upload_to='User/Profile_Picture', default='User/Profile_Picture/logo.png') city = models.CharField(max_length=50, blank=False, default=None) state = models.CharField(max_length=50, blank=False, default=None) birthdate = models.DateField(blank=False) bio = models.TextField(max_length=1000, blank=True, null=True) privacy = models.CharField(max_length=20, choices=PRIVACY_CHOICES, default='public', blank=False) requests = models.ManyToManyField(User, related_name='follow_request_user', default=None, blank=True) verified = models.BooleanField(default=False, blank=False) following_user = models.ManyToManyField(User, related_name='following_user', default=None, blank=True) followers = models.ManyToManyField(User, related_name='user_followers', default=None, blank=True) objects = models.Manager() def __str__(self): return self.name I want my response in JSON format so that i can use it in android app. I went through many blogs and Stackoverflow answers but any of that didn't give desired output In Short i just expect that client sends a username and get User and UserProfile in json format -
code works in code pen but not in vs code
I have a next button that's supposed to go to the next fieldset in a form. It works in the code-pen(https://codepen.io/atakan/pen/nPOZZR) in which I found it the. There were people asking about this same problem but the solution is supposed to be just adding the jquery cdn call but that did not work. anyone know whats up with this? (there is no error messages and I'm using Django version 4.2.3) this html: <!-- multistep form --> {%load static%} <head> <!-- ... your other links and scripts ... --> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-easing/1.3/jquery.easing.min.js"></script> <script src="{% static 'assets/js/profile_completion.js' %}"></script> <link rel="stylesheet" href="{% static 'assets/css/profile_completion.css' %}"> </head> <body> <form id="msform"> <!-- progressbar --> <ul id="progressbar"> <li class="active">Account Setup</li> <li>Social Profiles</li> <li>Personal Details</li> </ul> <!-- fieldsets --> <fieldset> <h2 class="fs-title">Create your account</h2> <h3 class="fs-subtitle">This is step 1</h3> <input type="text" name="email" placeholder="Email" /> <input type="password" name="pass" placeholder="Password" /> <input type="password" name="cpass" placeholder="Confirm Password" /> <input type="button" name="next" class="next action-button" value="Next" /> </fieldset> <fieldset> <h2 class="fs-title">Social Profiles</h2> <h3 class="fs-subtitle">Your presence on the social network</h3> <input type="text" name="twitter" placeholder="Twitter" /> <input type="text" name="facebook" placeholder="Facebook" /> <input type="text" name="gplus" placeholder="Google Plus" /> <input type="button" name="previous" class="previous action-button" value="Previous" /> <input type="button" name="next" class="next action-button" value="Next" /> </fieldset> <fieldset> … -
Django Confirmation Code Error (Two codes generated instead of one)
I am writing a class using Django that will handle getting a confirmation code from the user after they create an account. But when the function is called, the program creates a new random code, like it should. The issue comes in once the user enters this code and makes a post request. A new code it generated, and this is the one that the code the user entered will be compared with. Is there any way to get around this? @method_decorator(login_required, name='dispatch') class ConfirmEmail(View): def __init__(self, **kwargs: Any) -> None: super().__init__(**kwargs) self.code = str(random.randint(1000, 9999)) def get(self, request): email = request.GET.get('email') phone = request.GET.get('phone') send_mail( "Confirmation Code", "Your confirmation code is: " + self.code, "to_email", [email, ]) return render(request, "views/confirm_email.html") def post(self, request): confirmation_code = request.POST.get('confirmation_code', '') print(confirmation_code) print(self.code) if confirmation_code == self.code: return redirect('home') else: # The confirmation code is incorrect, display an error message. return render(request, "views/confirm_email.html", {'error_message': 'Invalid confirmation code'}) ``` -
Dependant dropdown
Dependant dropdown in html without javascript Can we write codes for dependant dropdown in html form in django project using html only dependant dropdown using html ,can you give any example codes for dependant dropdown without javascript -
How to send to the current channel room and the opposite channel room to show messages on both ends?
I was thinking of creating a model that handles saving and creating the groups like so: # Something like this perhaps... class OneOnOneRoom(models.Model): room_name = models.CharField(max_length = 100, unique=True) sender = models.ForeignKey(User, null=True, on_delete=models.CASCADE) receiver = models.ForeignKey(User, null=True, on_delete=models.CASCADE) def __str__(self): return f'Group {self.room_name} initiated by {self.sender} for {self.receiver}' Then in the connect method for my consumer I need to create two rooms somehow, so I could broadcast all the messages from user A or user B to be sent to both of the rooms so that both users can see each other messages. So if user A is http://localhost:8000:chat/B and user B is on http://localhost:8000:chat/A; user A should send data to his own channel and the channel for B; user B should send data to his own channel and the channel for B. Is this a good solution to do this? I can not think of any better solution right now– either way I found no way to actually send to multiple channels at once in channels. Any tips? What I have been trying and thinking: #asgi.py application = ProtocolTypeRouter({ "http": django_asgi_app, "websocket": AllowedHostsOriginValidator( AuthMiddlewareStack( URLRouter([ re_path(r"ws/chat/(?P<room_name>\w+)/$", ChatConsumer.as_asgi()), ]) ) ), }) #urls.py urlpatterns = [ path('<str:room_name>/', room), ] … -
Radio buttons in for loop only allows one selection for all iterations
I am working on building an attendance submission form (pictured below) in Django, but I am not currently using the Django Forms. I am having an issue with the radio buttons allowing only one selection for all iterations of the for loop. In the HTML, it loops through a list of students and within each of those iterations, it loops through a list of attendance types. Each attendance type is represented by a radio button because only one attendance type should be able to be chosen. However, this only allows one option to be selected for the whole for loop, instead of allowing one option to be chosen for each student. {% for student in list_of_students %} <tr> <td>{{student}}</td> <td> {% for attendanceType in list_of_attendanceTypes %} <input type="radio" name="attendancetype" id={{attendanceType}} value={{attendanceType.attendancetypeid}}> <label for={{attendanceType}}> {{attendanceType}}</label><br> {% endfor %} </td> <tr> {% endfor %} Is there a way to do this without changing the name of the buttons in each iteration of the for loop? Any help would be appreciated. -
Why docker displays only 3 messages from the 3rd WARNING level in the log, and 5 messages from the 1st DEBUGGING level on the localhost? How resolve?
I played a little in django docker with logging. And I don't understand why docker displays only 3 messages from the 3rd WARNING level in the log, and 5 messages from the 1st DEBUGGING level on the local host. Does anyone know what's going on? django code django logs Docker logs I tried add logging property to change default docker logger level, but it doesn't work. How set debug logging level in docker? -
Cannot pass non-database field from serializer to model
If I'm trying to do this by having changeReason = '' in model I get an error: TypeError: Got a `TypeError` when calling `Page.objects.create()`. This may be because you have a writable field on the serializer class that is not a valid argument to `Page.objects.create()`. You may need to make the field read-only, or override the PageSerializer.create() method to handle this correctly. I'm trying to achiveve this because I'm trying to use changeReason from jango-simple-history https://django-simple-history.readthedocs.io/en/2.8.0/historical_model.html#change-reason In model I can't use changeReason = models.CharField(max_length=300, blank=True, null=True, default=None) because I get another error column "changeReason" does not exist because it tries to find the column in page table and not in the history table. In the serializer the field is declared changeReason = serializers.CharField(write_only=True) -
Unable to install "url" package in pycharm
I am trying to install a "url" package in pycharm. But when installing I am getting error. I have installed Microsoft visualC++ and 'wheel' package too now. Please help. What else I can do to install it. Thanks. > Collecting url Using cached url-0.4.2.tar.gz (140 kB) Preparing metadata (setup.py): started Preparing metadata (setup.py): finished with status 'done' Collecting six (from url) Using cached six-1.16.0-py2.py3-none-any.whl (11 kB) Building wheels for collected packages: url Building wheel for url (setup.py): started Building wheel for url (setup.py): finished with status 'error' Running setup.py clean for url Failed to build url error: subprocess-exited-with-error python setup.py bdist_wheel did not run successfully. exit code: 1 [17 lines of output] Building from C++ C:\Users\User\PycharmProjects\Project1\env\lib\site-packages\setuptools\dist.py:745: SetuptoolsDeprecationWarning: Invalid dash-separated options !! ******************************************************************************** Usage of dash-separated 'description-file' will not be supported in future versions. Please use the underscore name 'description_file' instead. By 2023-Sep-26, you need to update your project and remove deprecated calls or your builds will no longer be supported. See https://setuptools.pypa.io/en/latest/userguide/declarative_config.html for details. ******************************************************************************** !! opt = self.warn_dash_deprecation(opt, section) error: Microsoft Visual C++ 14.0 or greater is required. Get it with "Microsoft C++ Build Tools": https://visualstudio.microsoft.com/visual-cpp-build-tools/ [end of output] note: This error originates from a subprocess, and is likely … -
Django relative path syntax
In this django project, the views.py in the 'basket' folder needs to import the 'Product' class from the 'store' folder. These two folders are at the same level, from the top folder. But 'from store.models import Product' gives an 'unresolved reference' error. I've tried several permutations, to no avail. Please help. I've tried using one dot, and two dots before 'store'. With two dots it goes too far up in the folders structure, with one it still shows 'unresolved reference for the 'store' folder. enter image description here -
if one user login send message creating one message at a time 2 users login send a message create 2 messages
how to avoid dulpicate message creatinhg 2 users login at a one time class ChatConsumer(WebsocketConsumer): def connect(self): print("here") self.room_name = self.scope["url_route"]["kwargs"]["room_name"] self.room_group_name = f"chat_{self.room_name}" query_string = self.scope['query_string'].decode('utf-8') query_params = parse_qs(query_string) if 'user_id' in query_params: user_id = query_params['user_id'][0] print("userid.......................................................................................", user_id) user = self.authenticate_user(user_id) if user.is_authenticated: print("sucess authentication....................") # Join room group async_to_sync(self.channel_layer.group_add)( self.room_group_name, self.channel_name ) self.accept() def disconnect(self, close_code): # Leave room group async_to_sync(self.channel_layer.group_discard)( self.room_group_name, self.channel_name ) def authenticate_user(self, user_id): def sync_authenticate_user(): try: user = User.objects.get(id=user_id) self.scope['user'] = user except User.DoesNotExist: self.scope['user'] = AnonymousUser() thread = threading.Thread(target=sync_authenticate_user) thread.start() thread.join() return self.scope['user'] def receive(self, text_data=None, bytes_data=None): # parse the json data into dictionary object text_data_json = json.loads(text_data) if text_data_json.get('action') == 'get_chat_history': conversation = Conversation.objects.get(id=int(self.room_name)) all_messages = Message.objects.filter( conversation_id=conversation).order_by('timestamp') serializer = MessageSerializer(instance=all_messages, many=True) message_list = serializer.data self.send(text_data=json.dumps({ 'type': 'message_list', 'messages': message_list })) else: chat_type = 'chat_message' return_dict = { 'type': chat_type, 'message': text_data_json.get('message'), 'attachment': text_data_json.get('attachment') } async_to_sync(self.channel_layer.group_send)( self.room_group_name, return_dict ) def chat_message(self, event): print("event.............................................................................................", event) text_data_json = event.copy() text_data_json.pop("type") message = event.get("message", None) attachment = event.get("attachment", None) print(message, attachment, "........................................................................") conversation = Conversation.objects.get(id=int(self.room_name)) sender = self.scope['user'] sender_id = sender.id print("username is...............................................................", sender) print("user is...................", sender_id) print(conversation.id,"converstaionid") sender_id = self.scope['user'].id message = event.get("message", None) attachment = event.get("attachment", None) conversation = Conversation.objects.get(id=int(self.room_name)) if attachment: file_str, … -
checkboxinput overlaid on the label
I am working with a form in django with crispy form and it has many fields, and the checkboxinput field does not render well in the html, it is overlapped in the label and very big. previously i was using another template style but when i changed the html, the checks were broken form.py class TestForm(forms.ModelForm): class Meta: model = Test fields = [ 'test1', 'test2' ] labels = { 'test1':'Test 1', 'test2':'Test 2',} widgets = { 'test1':forms.CheckboxInput(attrs={'class':'form-check-label'}), 'test2':forms.CheckboxInput(attrs={'class':'form-check-label'}), form.html <div class="form-group col-md-4 d-flex align-items-center pt-4 pl-2"> {{ form.test1 | as_crispy_field }} </div> <div class="form-group col-md-4 d-flex align-items-center pt-4 pl-2"> {{ form.test2 | as_crispy_field }} </div> This is how the checkboxes and the labels look -
Why is django ManyToManyField asymmetric?
A classic example of a ManyToManyField (django 4.2 docs or SO) looks something like this: class Person(models.Model): name = models.CharField(max_length=128) class Group(models.Model): name = models.CharField(max_length=128) members = models.ManyToManyField(Person, through='Membership') class Membership(models.Model): person = models.ForeignKey(Person, on_delete=models.CASCADE) group = models.ForeignKey(Group, on_delete=models.CASCADE) date_joined = models.DateField() invite_reason = models.CharField(max_length=64) Why the asymmetry? We have this natural scheme where a Person can belong to Groups through a Membership and vice versa. So why does Person make no reference to this? Or, perhaps better phrased, why does the framework see fit to encourage us to state the relationship only on one side? # No one writes this: class Person(models.Model): name = models.CharField(max_length=128) groups = models.ManyToManyField(Group, through='Membership') -
django, get one child for every parent
the tables i have some items (Monitors, Printers etc). The items may change owner and i keep history of all the owners. i want to get only the most recent owner (owner's change date) for each item, ordered by owner's name. For example: table items item_id brand serial 1 BrandA s22222 2 BrandB s33333 3 BrandC s11111 table owners name is owner's name, date is when the item changes owner. (in the example item 1 had 2 owners and item 2 had 3 owners. owner_id item_id name date 1 2 B 2023-6-22 2 3 D 2023-6-30 4 2 F 2023-6-20 3 1 A 2023-6-25 4 2 E 2023-6-21 5 1 C 2023-6-26 i want the next table as result: owner_id brand serial item_id name date 1 BrandB s33333 2 B 2023-6-22 5 BrandA s22222 1 C 2023-6-26 2 BrandC s11111 3 D 2023-6-30 and i think the sql below gives what i want. Select * From (SELECT *, MAX(date) as last_date FROM owners GROUP BY owner_id) as my_owners INNER JOIN items on owners.owner_id = items.owner_id ORDER BY last_date the problem is i cant find a way to do it with a django queryset (btw i use sqlite3 db) the models.py … -
No Reverse match after using slug
I have been trying to adopt slugs in Django project to give beautiful urls since i have more than one app in the Django project but I have encountered this error. Am stuck and I do not know to sort it out. The following are appname/models.py code class Standard(models.Model): name = models.CharField(max_length=100, unique=True) slug = models.SlugField(null=True, blank = True) description = models.TextField(max_length=500, blank=True) def __str__(self): return self.name def save(self, *args, **kwargs): self.slug = slugify(self.name) return super().save(*args, **kwargs) class Subject (models.Model): subject_id = models.CharField(max_length=100, unique= True) name = models.CharField(max_length=100, unique=True) slug = models.SlugField(null=True, blank=True) standard = models.ForeignKey(Standard,on_delete=models.CASCADE,related_name="subjects") image = models.ImageField(upload_to=save_subject_img, blank=True,verbose_name='Subject Image') description = models.TextField(max_length=500, blank=True) def __str__(self): return self.name def save(self, *args, **kwargs): self.slug = slugify(self.subject_id) return super().save(*args, **kwargs) class Lesson (models.Model): lesson_id = models.CharField(max_length=250, unique=True) standard = models.ForeignKey(Standard, on_delete=models.CASCADE) created_by = models.ForeignKey(User, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) subject = models.ForeignKey(Subject, on_delete=models.CASCADE, related_name="lessons") name = models.CharField(max_length=250) position = models.PositiveSmallIntegerField(verbose_name="chapter no.") slugs = models.SlugField(null=True, blank=True) class Meta: ordering = ['position'] def __str__(self): return self.name def save(self, *args, **kwargs): self.slug = slugify(self.name) return super().save(*args, **kwargs) Then the following is my urls.py file in the app directory app_name = 'appname' urlpatterns = [ path('',views.StandardListView.as_view(),name='standard_list'), path('<slug:slug>', views.SubjectListView.as_view(), name='subject_list'), path ('<str:standard>/<slug:slug>/', views.LessonListView.as_view(),name='lesson_list'), ] Everything was working … -
How to use coalesce function in Django ORM?
I have a sql query whose coalesce portion that looks like below "coalesce(MAX(case when status = 'OK' then 'OK' end),'') as final_status" I am writing the same query in Django ORM. But I am not getting any value for the coalesce portion. This is how the coalesce portion looks like .annotate(final_status=Max(Coalesce( Case( When(status__contains=['OK'], then=Value('OK')), default=Value(''), output_field=CharField() ), Case( When(~Q(notify__contains=['OK']), then=Value('')), default=Value(''), output_field=CharField() ) ))) In regular sql query, I am getting values in final_status column but in django query, the final_status column is empty for all the rows What am I doing wrong? -
In Django i have problems with HTMX: a dependent combobox doesn't work. The first combobox is populated, the second is empty
I have a country combobox and a trip combobox. Both are employees. They use the same table of a database (i don't want to use two tables with foreignkey). I think I came close to the solution, but something is not working. The first combobox is populated correctly, while the second combobox is empty. For example if I select Spain in Country, in the combobox trip I should see: Madrid-Barcelona, and then Sevilla-Bilbao, because they are in the same database table: ID | COUNTRY | DEPARTURE | DESTINATION | | france | paris | lyon | | france | marseilles| grenoble | | spain | madrid | barcelona | | spain | seville | bilbao | models.py from django.db import models class Trip(models.Model): country = models.CharField(max_length=100) departure = models.CharField(max_length=100) destination = models.CharField(max_length=100) @property def journey(self): return f"{self.departure}-{self.destination}" urls.py from django.urls import path from . import views urlpatterns = [ path('', views.trip_selector, name="trip_selector"), path('', views.trips, name='trips') ] form.html {% extends 'base.html' %} {% block content %} <!-- First Combobox --> <label for="id_country">Country</label> <select name="country" id="id_country" hx-get="{% url 'trips' %}" hx-target="#id_trip" hx-indicator=".htmx-indicator"> {% for country in countries %} <option value="{{ country }}">{{ country }}</option> {% endfor %} </select> <!-- Second Combobox ??????? …