Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
AWS ECS Fargate - django runserver will be billed 24/7?
I have a django app in a dockerfile, and I deployed it with ECS Fargate. It works well, but I'm am not sure about how pricing works. python manage.py runserver has to be running all the time because it needs to be listening the incoming requests. Does it mean that my fargate is beign used 24/7. and subsequently billed 24/7?. If that is true, what is the correct way to use a monolithic app in a fargate container minimizing costs? Dockerfile FROM python:3.11-alpine RUN mkdir /app WORKDIR /app COPY . . RUN sed -i 's/\r$//g' ./local/entrypoint.sh RUN chmod +x ./local/entrypoint.sh RUN pip install -r ./local/requirements.txt EXPOSE 8000 ENTRYPOINT ["/bin/sh", "./local/entrypoint.sh"] entrypoint.sh #!/bin/sh set -o errexit set -o pipefail set -o nounset echo "------- RUNNING DJANGO COMMANDS -------" python /app/manage.py makemigrations python /app/manage.py migrate python /app/manage.py runserver 0.0.0.0:8000 -
WhatsApp FLows - Could not decrypt the response received from the server
I'm trying to generate the response for the WhatsApp flow using the WhatsApp bussines api with the following code ` def post(self, request, *args, **kwargs): try: dict_data = json.loads(request.body.decode('utf-8')) encrypted_flow_data_b64 = dict_data['encrypted_flow_data'] encrypted_aes_key_b64 = dict_data['encrypted_aes_key'] initial_vector_b64 = dict_data['initial_vector'] flipped_iv = self.flip_iv(initial_vector_b64.encode('utf-8')) encrypted_aes_key = b64decode(encrypted_aes_key_b64) key_private = open('*******.pem', 'rb').read().decode('utf-8') private_key = load_pem_private_key(key_private.encode('utf-8'), password="*************".encode('utf-8')) aes_key = private_key.decrypt(encrypted_aes_key, OAEP(mgf=MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None)) aes_key_b64 = b64encode(aes_key).decode('utf-8') flow_data = b64decode(encrypted_flow_data_b64) key = b64decode(aes_key_b64) iv = b64decode(initial_vector_b64) encrypted_flow_data_body = flow_data[:-16] encrypted_flow_data_tag = flow_data[-16:] cipher = Cipher(algorithms.AES(key), modes.GCM(iv,encrypted_flow_data_tag)) decryptor = cipher.decryptor() decrypted_data = decryptor.update(encrypted_flow_data_body) + decryptor.finalize() flow_data_request_raw = decrypted_data.decode("utf-8") hello_world_text = "HELLO WORLD" response_data = { "version": "3.0", "screen": "MY_FIRST_SCREEN", "data": { "hello_world_text": hello_world_text } } response_json = json.dumps(response_data) # Obtendo a chave AES após descriptografar encrypted_aes_key fb_aes_key = private_key.decrypt(encrypted_aes_key, OAEP(mgf=MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None)) # Usando a chave AES para criptografar a resposta response_cipher = Cipher(algorithms.AES(fb_aes_key), modes.GCM(iv)) encryptor = response_cipher.encryptor() encrypted_response = ( encryptor.update(response_json.encode("utf-8")) + encryptor.finalize() + encryptor.tag ) encrypted_response_b64 = b64encode(encrypted_response).decode("utf-8") # Construct the final response final_response = { "encrypted_flow_data": encrypted_response_b64, "encrypted_aes_key": encrypted_aes_key_b64, "initial_vector": initial_vector_b64 } return JsonResponse(final_response, status=200) except Exception as e: print(e) return HttpResponse(status=500, content='ok') def flip_iv(self, iv): flipped_bytes = [] for byte in iv: flipped_byte = byte ^ 0xFF flipped_bytes.append(flipped_byte) return bytes(flipped_bytes) ` The entire … -
Problem deploying Dockerised Django app in Heroku and Fly
I've successfully deployed my Django app with Fly.io. But ever since I followed William Vincent's 'Django for Professionals' by trying to Dockerise my project, I have had no luck with updating my production server. In fact, I cannot deploy at all anymore. I ran heroku logs --tail and this is what I got. May you please offer any explanation as to why my 'release command' is failing? heroku logs --tail » Warning: heroku update available from 7.53.0 to 8.6.0. 2023-10-23T12:37:29.030037+00:00 app[api]: Initial release by user 2023-10-23T12:37:29.030037+00:00 app[api]: Release v1 created by user 2023-10-23T12:37:29.160630+00:00 app[api]: Enable Logplex by user 2023-10-23T12:37:29.160630+00:00 app[api]: Release v2 created by user 2023-10-23T12:39:34.797658+00:00 app[api]: Stack changed from heroku-22 to container by user 2023-10-23T12:39:34.813238+00:00 app[api]: Upgrade stack to container by user 2023-10-23T12:39:34.813238+00:00 app[api]: Release v3 created by user 2023-10-23T12:49:12.780220+00:00 app[api]: Attach DATABASE (@ref:postgresql-clean-38410) by user 2023-10-23T12:49:12.780220+00:00 app[api]: Running release v4 commands by user 2023-10-23T12:49:12.794484+00:00 app[api]: Release v5 created by user 2023-10-23T12:49:12.794484+00:00 app[api]: @ref:postgresql-clean-38410 completed provisioning, setting DATABASE_URL. by user 2023-10-23T12:53:19.000000+00:00 app[api]: Build started by user 2023-10-23T12:54:06.000000+00:00 app[api]: Build succeeded 2023-10-23T12:54:06.158579+00:00 app[api]: Deploy e59a06da by user 2023-10-23T12:54:06.158579+00:00 app[api]: Running release v6 commands by user 2023-10-23T12:54:06.997250+00:00 app[api]: Starting process with command `/bin/sh -c 'if curl $HEROKU_RELEASE_LOG_STREAM --silent --connect-timeout 10 --retry … -
Django sessions for anonymous users get deleted when logging in: how to handle shop baskets?
I'm building a webshop where we want anonymous users to also be able to add things to their basket. I thought I'd be smart and created a Basket model like this: class Basket(models.Model): owner = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True, on_delete=models.CASCADE) session = models.ForeignKey(Session, blank=True, null=True, on_delete=models.CASCADE) So for logged in users I'd assign the owner field, and for anonymous users I'd assign the session field. Then when the session expires the basket would also be cleaned up, so I wouldn't end up with a ton of database records for baskets that can never be checked out anymore. So far so good. When an anonymous user logs in, I want to assign the basket to that user. And this is where the complications start to add up because when a user logs in they get a new session key, which is not accessible in the request. While I could create some kind of middleware that keeps track of the previous session key, the biggest problem is that by the time user_logged_in signal is called, the session record has already been deleted from the database and thus my basket has also been deleted. I could do a few things, but none seem very … -
Shipping event created from the dashboard does not call handle_shipping_event (django-oscar)
I'm trying to change the shipping event type from the django oscar admin dashboard and send an email to the customer but it seems like it doesn't call the handle_shipping_event under order/processing.py So far, I created a shipping event type and associated it with a communication event type. Then I inherited order/processing.py and add a send email function, however, it seems the shipping event created from the dashboard doesn't call handle_shipping_event under order/processing.py. I can see the shipping event written to the db. from oscar.apps.order.processing import EventHandler as CoreEventHandler class EventHandler(CoreEventHandler): def handle_shipping_event(self, order, event_type, lines, line_quantities, **kwargs): print('It does not print this') # Example implementation self.validate_shipping_event( order, event_type, lines, line_quantities, **kwargs) # send tracking mail self.send_shipped_email(order) return self.create_shipping_event( order, event_type, lines, line_quantities, **kwargs) django-oscar version: 3.1 Python 3.8.10 Thanks -
Customizing PasswordResetView using Django auth views
Well, I need to create a customized view based on Django's PasswordReset view, but for when the User is already logged in. I originally used PasswordChangeView for this, but it automatically redirect the user to PasswordChangeForm, where the user inputs the older password and the new password and then save it. But, for a matter of security, I was requested to, when the user clicks the link to change their password, it automatically send a Password Reset email to they, showing the 'password_reset_done.html' and sending the password reset password. (Don't know if I'm making myself really clear I'm currently studying and this is my first time using stack overflow. I already a custom_password_change view that uses PasswordResetView. `def custom_password_change(request): if request.method == "POST": user = request.user if user.is_authenticated: # Call the Django built-in view for password reset return PasswordResetView.as_view( template_name='registration/password_change_form.html', email_template_name='registration/password_change_email.html', success_url='/password_change/done/' )(request) return render(request, "registration/password_change_form.html")` But it stills demands user to input their email on the PasswordResetForm and then sends the email. I need it to send the email when the user clicks "change password" instead and returning the 'password_reset_done.html' template. -
Is it possible to add a child page from a form in the frontend in Wagtail CMS?
Is it possible to add a child page from a form in the frontend in Wagtail CMS? The reason for this is that when I use the formbuilder the content added is in the Forms section, but I want the content from the form to be a page on its own as this is primary content in the application I built. I was thinking this is possible with the API, but I would think there would be a better solution? -
Django : is it possible to display multiple edit forms as one consolidated form in django admin?
I have three EDIT forms, an environment has one or multiple machines, then a machine has one or multiple users. Now my question is there a way to display the three EDIT forms in one consolidated form with one save button. I want to display three tabs one for Environment and one for Machines (multiple) and one for Users (Multiple), Similar to this : I have already achieved similar results using custom HTML template, but I'm not satisfied, it would be better if I got it done using Django admin configurations my current solution : <div class="tab-content mt-3" id="pills-tabContent"> <div class="tab-pane fade show active" id="environment" role="tabpanel" aria-labelledby="environment-tab"> <div class="step"> <h2>Environment general information</h2> {% for field in environment_form %} <div class="fieldWrapper"> {{ field.errors }} {{ field.label_tag }} {{ field }} {% if field.help_text %} <p class="help">{{ field.help_text|safe }}</p> {% endif %} </div> {% endfor %} </div> </div> <div class="tab-pane fade" id="machine" role="tabpanel" aria-labelledby="machine-tab"> <div class="step"> <h2>Machines information</h2> {% for machine_form in machine_forms %} <h3>Machine {{ forloop.counter }}</h3> {% for field in machine_form %} <div class="fieldWrapper"> {{ field.errors }} {{ field.label_tag }} {{ field }} {% if field.help_text %} <p class="help">{{ field.help_text|safe }}</p> {% endif %} </div> {% endfor %} {% if … -
Celery worker is not starting for my django project hosted on elastic beanstalk
Good day by co-developers. I have a project working on aws elasticbeanstalk and i want to integerate celery to it but the celery worker is not starting and everything is workking fine in development but when i deploy it to elastic ebeanstalk it wont start the worker. my question is that is there any way to start the celery worker or i am during it wrong. below is my Procfile file where i start it with the error i am getting the coonsoole and the log in the instance. thanks in advance. Procfile web: gunicorn --timeout 90 ayjayproject.wsgi celery_beat: celery -A ayjayproject.celery beat -l INFO celery_worker: celery -A ayjayproject.celery worker -l INFO -P solo Log fiile 2023/10/23 10:35:00.909620 [INFO] Running command /bin/sh -c systemctl show -p PartOf celery_beat.service 2023/10/23 10:35:00.919175 [INFO] Running command /bin/sh -c systemctl is-active celery_beat.service 2023/10/23 10:35:00.927731 [INFO] Running command /bin/sh -c systemctl start celery_beat.service 2023/10/23 10:35:00.958395 [INFO] Registering the proc: celery_worker 2023/10/23 10:35:00.958424 [INFO] Running command /bin/sh -c systemctl show -p PartOf celery_worker.service 2023/10/23 10:35:00.975817 [INFO] Running command /bin/sh -c systemctl daemon-reload 2023/10/23 10:35:01.145963 [INFO] Running command /bin/sh -c systemctl reset-failed 2023/10/23 10:35:01.159697 [INFO] Running command /bin/sh -c systemctl is-enabled eb-app.target 2023/10/23 10:35:01.171728 [INFO] Running command … -
Import iso_date_prefix from django_minio_backend problem
I have this exception when running django dev-server: File "/Users/maxim/PycharmProjects/inventory3/inventory/main/models.py", line 22, in <module> **from django_minio_backend import iso_date_prefix** File "/Users/maxim/PycharmProjects/inventory3/venv/lib/python3.11/site-packages/django_minio_backend/__init__.py", line 1, in <module> from .apps import * File "/Users/maxim/PycharmProjects/inventory3/venv/lib/python3.11/site-packages/django_minio_backend/apps.py", line 3, in <module> from .models import MinioBackend, MinioBackendStatic File "/Users/maxim/PycharmProjects/inventory3/venv/lib/python3.11/site-packages/django_minio_backend/models.py", line 30, in <module> from django.utils.timezone import utc **ImportError: cannot import name 'utc' from 'django.utils.timezone'** It started from updating Python's packages to latest versions... -
DRF serializer for many-to-many through tree
here are my models (simplified): class Template(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) title = models.CharField(max_length=255) areas = models.ManyToManyField("Area", through="AreasOrder") class Area(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) title = models.CharField(max_length=255) items = models.ManyToManyField("Item", through="ItemsOrder") class Item(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) title = models.CharField(max_length=255) further_into_tree= models.ManyToManyField("SomeModel", through="SomeModelOrder") class AreasOrder(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) template = models.ForeignKey(Template, on_delete=models.SET_NULL, null=True) area = models.ForeignKey(Area, on_delete=models.SET_NULL, null=True) class ItemsOrder(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) area = models.ForeignKey(Area, on_delete=models.SET_NULL, null=True) item = models.ForeignKey(Item, on_delete=models.SET_NULL, null=True) I want to build serializer for getting template by id with all it depedencies. I'm struggling with putting items into area serializer. Can you help me? Serializers: class TemplateSerializer(serializers.ModelSerializer): areas = AreaSerializer(many=True, source="areasorder_set") class Meta: model = Template fields = ("id", "title", "areas", ) class AreaSerializer(serializers.ModelSerializer): items = serializers.SerializerMethodField() order_id = serializers.SerializerMethodField() id = serializers.ReadOnlyField(source="area.id") title = serializers.ReadOnlyField(source="area.title") def get_order_id(self, obj): return obj.id def get_items(self, obj): How to access items assigned to area? return ItemSerializer(many=True, source=obj.area.itemsorder_set) # doesn't work - raises error "'RelatedManager' object is not iterable" class Meta: model = AreasOrder fields = ( "id", "title", "items", "order_id" ) I also tried basing AreaSerializer on model Area: class AreaSerializer(serializers.ModelSerializer): items = ItemSerializer(many=True, required=False) class Meta: model = Area fields … -
additional fields in ModelSerializer with override update in django
I have a product model like this: class Product(models.Model): title = models.CharField(max_length=200) description = models.TextField(blank=True, null=True) category = models.ForeignKey(ProductCategories, on_delete=models.CASCADE) brand = models.ForeignKey(ProductBrand, on_delete=models.SET_NULL, blank=True, null=True) score = models.PositiveIntegerField(blank=True, null=True) insurnace = models.PositiveIntegerField(blank=True, null=True) property = models.ManyToManyField(ProductProperty, blank=True) is_flagship = models.BooleanField(default=False) is_exhibition = models.BooleanField(default=False) seen = models.IntegerField(default=0) for saving images, prices and details i wrote this three model: class ProductImage(models.Model): image = models.ImageField(upload_to='product_image/') product = models.ForeignKey(Product, related_name='image', on_delete=models.SET_NULL, blank=True, null=True) is_main_image = models.BooleanField(default=False) class ProductDetail(models.Model): title = models.ForeignKey(ProductDetailTitle, related_name='value', on_delete=models.CASCADE) value = models.CharField(max_length=500) product = models.ForeignKey(Product, related_name='detail', on_delete=models.CASCADE) class ProductPrice(models.Model): product = models.ForeignKey(Product, related_name='price', on_delete=models.CASCADE) color = models.ForeignKey(ProductColor, on_delete=models.CASCADE) price = models.PositiveIntegerField() quantity = models.PositiveIntegerField() i wrote this serializer for manage product class ProductAdminSerializer(serializers.ModelSerializer): images = serializers.ListSerializer(child=serializers.IntegerField()) prices = ProductPriceForProductAdminSerializer(many=True) properties = serializers.ListSerializer(child=serializers.IntegerField()) details = ProductDetailForProductAdminSerializer(many=True) class Meta: model = Product fields = ['id', 'title', 'category', 'brand', 'images', 'description', 'properties', 'is_flagship', 'is_exhibition', 'prices', 'score', 'insurnace', 'details'] def create(self, validated_data): title = validated_data.get('title') category = validated_data.get('category') brand = validated_data.get('brand') description = validated_data.get('description') is_flagship = validated_data.get('is_flagship') is_exhibition = validated_data.get('is_exhibition') score = validated_data.get('score') insurnace = validated_data.get('insurnace') product = Product.objects.create(title=title, category=category, brand=brand, description=description, is_flagship=is_flagship, is_exhibition=is_exhibition, score=score, insurnace=insurnace) image_ids = validated_data.get('images') ProductImage.objects.filter(id__in=image_ids).update(product=product) properties = validated_data.get('properties') if properties is not None: property_objs = ProductProperty.objects.filter(id__in=properties) product.property.set(property_objs) prices … -
Django JSONB find value less than
I have a sample JSONB dataset below, this is one column entry from a single row: [ { "id": "xxx", "type": "thing", "value": { "date": "2023-10-21" } }, { "id": "xxy", "type": "thing", "value": { "date": "2023-10-19" } } ] I need to find if one of the 'date' values is less than 'some_value' - please see pseudocode below: Q(columnName__{arrayOfItems}__value__date__lt=some_value) I can find if an exact value exists but need the value to be variable, for example the below works: Q(columnName__contains=[{"value": {"date": "2023-10-21"}}]) I think I need to add a subquery for the date itself ("2023-10-21") to see if it is less than some other date but currently unable to do this. Spent a few days so far, any comments welcome to help guide me. Many thanks in advance. -
feign client response does not retrive cookie named sessionid while postman does
I have to connect to django web application using feign client. First, i checked the flow in postman. In postman I'm using GET on myapp/accounts/login/?next=/ and retrive csrftoken as entry Set-Cookie in response headers I'm using POST on myapp/accounts/login/?next=/ with body as x-www-form-urlencoded "username=login&password=password&csrfmiddlewaretoken=token&next=/" and retrive NEW csrftoken and sessionid as entry in Set-Cookie. The response code is 302 (Found) I need those two cookies to use as request headers with another endpoints and i checked it's working fine The problem is that i cannot reproduce the same in feign client which i have to use The feign response from POST doesn't have second cookie (sessionId) The csrftoken is not refreshed I think i was trying almost everything : cookieinterceptor, turning off follow redirects in okhttp client, session interceptor in okhttp My simple code looks like : public class Main { private static final String AUTHENTICATION_TEMPLATE = "username=%s&password=%s&csrfmiddlewaretoken=%s&next=/"; public static void main(String[] args) throws IOException { RouteClient routeClient = Feign.builder() .client(new OkHttpClient()) .logger(new CustomFeignLogger()) .logLevel(Logger.Level.FULL) .encoder(new JacksonEncoder()) .decoder(new JacksonDecoder()) .target(RouteClient.class, DataInput.url); Response getResponse = routeClient.getToken(); String cookie = extractCookie(getResponse); String token = extractToken(cookie); Response postResponse = routeClient.postDataWithParametersInBody(insertHeaderMap(token), insertBody(AUTHENTICATION_TEMPLATE, token)); System.out.println(postResponse); } public static String insertBody(String template, String token) { return … -
Task threadpoolexecutor disappeared suddenly after 10 minutes of running - python
The Task that created using ThreadPoolExecutor disappear if they are not completed within 10 minutes, this makes me unable to execute tasks that run for a long time. I'm running a background scheduler in Django with an execution time window of every 5 seconds. scheduler = BackgroundScheduler() scheduler.add_job(start_etl_caller, 'interval', seconds=5) def execute_api(etl_id, endpoint, is_running, updated_at, threshold_time): try: print(f'start etl caller - etl_id : {etl_id}') x = requests.get(endpoint) print(endpoint, x.content) print(f'end etl caller - etl_id : {etl_id}') except: raise update_state(etl_id, False) def start_etl_caller(): etl_list = get_active_apis() threshold_time = (timezone.localtime() - timedelta(hours=1)).replace(tzinfo=None) executor = ThreadPoolExecutor() for etl_record in etl_list: if etl_record[2]: if etl_record[3] <= threshold_time: update_state(etl_record[0], False) continue update_state(etl_record[0], True) try: executor.submit(execute_api, etl_record[0], etl_record[1], etl_record[2], etl_record[3], threshold_time) except: raise The task is to call the API using ThreadPoolExecutor, so that processes do not wait for each other. However, if requests.get(endpoint) takes more than 10 minutes, the code after that will not be executed (print - update). My assumption is that tasks created using ThreadPoolExecutor will automatically disappear if the process does not complete before 10 minutes. Is there any enlightenment on how I can solve this problem? I want my task to continue running even though 10 minutes have passed. Thank You! -
Is There a Django Library for Email-Based OTP Password Resets?
I recently transitioned my Django project from a web app to a mobile app. While Djoser worked great for password resets on the web using UIDs and tokens, this approach doesn't work well on mobile due to the lack of explicit URLs. I'd like to avoid deep linking, as it seems it might be error-prone. So, I'm trying to figure out a different approach that lets users reset their passwords through email. I'm considering a one-time password (OTP). However, I haven't found a specific library that offers this feature. Could someone please help? Or, are there better ways to reset passwords via email other than using OTP? Thank you! -
How to get user groups from Django?
I'm trying to get the user groups that exist in a user in Django but unfortunately in the console it says: Uncaught ReferenceError: user is not defined at 6/:643:33 The function is supposed to redirect the user depending on if he has those groups or not. This is my current code: if (data.includes('The process is done.')) { alert('Success!.'); setTimeout(function () { if (user.groups.filter(name='group1').exists() || user.groups.filter(name='group2').exists()) { window.location.href = "{% url 'red' %}"; } else { window.location.href = "{% url 'blue' %}"; } }, 2000); } The code above is inside a success AJAX function. -
can using multiple threads in python and sending a POST request to the same api endpoint cause problems?
I'm currently using 3 threads to run my django app and I've noticed sporadic errors in the return response from a POST request that I'm making that uploads some info unto a database. responseObject = requests.post(url, params=params) I'll get an error back saying that "the entry already exists",now I don't control this endpoint myself so I can't look into it but I guess that particular message is irrelevant since I make sure that each request is different and also the error appears randomly and I can't really replicate it. I have ruled out anything wrong with the parameters, url or anything like that in this case. My suspicion is that the error comes from the threads making the request at the same time or something like that. Now I've read that django is supposedly thread safe and that the requests library in python is also thread safe so I don't know why it would cause trouble, I don't think these 3 requests would cause any trouble for the endpoint as a server is most likely made to handle concurrent web requests? I have tried making this request under a lock like lock = threading.Lock() with lock:responseObject = requests.post(url, params=params) and … -
how to display the names of all my applied filters in django, and then remove one by one or any filter just by clicking on it
Problem Statement I am working on a data filtering project using Django, and I want to implement a feature where applied filters are displayed on the screen, and users can remove them by clicking on a cross (X) button next to the filter name. Requirements When a filter is applied, it should be displayed at the top of the screen with a cross (X) button, allowing users to remove that specific filter. For example, if I apply a filter for charge_holder_name with the value 'rock', the filter name 'charge_holder_name', so it should be shown at the top of the screen with a cross button, so I can remove this filter by clicking on it. The same case should apply when multiple filters are applied, such as 'date', 'amount', 'id', etc. All applied filter names should be displayed at the top of the screen. Implementation Filters.py from bootstrap_datepicker_plus.widgets import DateTimePickerInput import django_filters from .models import RocCharge, RocCompany from django import forms # You can use a set comprehension to get unique values from RocCharge, loop to get unique values unique_charge_holder_names = {i.charge_holder_name for i in RocCharge.objects.all()} unique_company_names = {company.company_name for company in RocCompany.objects.all()} class Orderfilter(django_filters.FilterSet): # Specify the choices as a … -
How can I order a Django query by a field of a related model?
I have these two models, ChatRoom and ChatMessage, which are related. My goal is to order the ChatRoom queries in a way that the room with the most recent message, as determined by the sent_timestamp, appears at the top of the results. While I've found some similar questions on this platform, none of them seem to precisely address my specific issue. I'm aware of the annotate method, which I can use to achieve this outside of the model's Meta class, but I'm interested in setting the ordering directly in the Meta class of the ChatRoom model. Is there a way to achieve this ordering within the Meta class, or is there an alternative approach I should consider? class ChatRoom(models.Model): members = models.ManyToManyField(User, related_name="chat_rooms") class Meta: # Intended for this to order the chat rooms so that the room that # has the most recent chat message come first, but it's not working ordering = ("-messages__sent_timestamp",) class ChatMessage(models.Model): room = models.ForeignKey(ChatRoom, models.CASCADE, related_name="messages") sender = models.ForeignKey(User, models.CASCADE) text = models.TextField(validators=[MaxLengthValidator(280)]) sent_timestamp = models.DateTimeField(auto_now_add=True) delivery_timestamp = models.DateTimeField(null=True, blank=True) read_timestamp = models.DateTimeField(null=True, blank=True) class Meta: ordering = ("-sent_timestamp",) This is the test I've written to check the ordering, but it's failing at this … -
python-docx Hyperlink The hyperlink is created but not clickable
I was taking tuples from the database and creating a document with those values. Among them, I needed a hyperlink, so I wrote a function for it. However, the document was created, but it didn't work when I clicked on it, so when the document is completed and I do additional line break processing, It's working fine. Please tell me about this problem! def add_hyperlink(paragraph,text, url): # Create a new hyperlink element hyperlink = OxmlElement('w:hyperlink') hyperlink.set(qn('w:anchor'), url) # 하이퍼링크 URL 설정 # Create ‘w:t’, a sub-element of hyperlink t = OxmlElement('w:t') t.text = text hyperlink.append(t) # Show hyperlink text in blue run = paragraph.add_run() run._r.append(hyperlink) run.font.color.rgb = RGBColor(0, 0, 255) In the text, it is used like this: p1 = doc.add_paragraph(f"file : ", style='Normal') add_hyperlink(p1,base_url + path, base_url + path) run = p1.runs[0] run.add_break(WD_BREAK.LINE) # 줄바꿈 추가 -
In vs code django rest framework not showing autocomplete
This is my setting.json { "files.autoSave": "afterDelay", "python.defaultInterpreterPath": "/bin/python", "python.analysis.indexing": true, } Why vscode not show autocomplete for django rest framework? -
Django Admin page queryset dynamic filter
in the following Django Admin page I want the Model query set to be filtered by the Brand_id whenever adding a year This is the way that my models are setup: class Brand(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class Model(models.Model): name = models.CharField(max_length=100) brand = models.ForeignKey(Brand, on_delete=models.CASCADE) def __str__(self): return self.name class Year(models.Model): year = models.IntegerField() brand = models.ForeignKey(Brand, on_delete=models.CASCADE, default= None, blank = True, null= True) model = models.ForeignKey(Model, on_delete=models.CASCADE, default=None) def __str__(self): return str(self.year) I tried many attempts and searched for solutions but all of them in vain. My starting point now is to use the get_form function in the following way: class YearAdmin(admin.ModelAdmin): list_display = ['year', 'model', 'brand'] list_filter = ['brand', 'model'] def get_form(self, request, obj=None, **kwargs): form = super().get_form(request, obj, **kwargs) form.base_fields["model"].queryset = Model.objects.filter(brand_id=2) return form instead of having "brand_id=2" I would like to have something like "brand_id = currently_chosen_brand_id" in a dynamic way. How can this be done? Thank you in advance! -
After submitting the Booking form, there's nothing in the database
I've been trying to get this form to work. I created the model, forms.py, views, and linking in the URL files. The form was submitted and I got the 200 status code, so it seems like the POST method went through, but when I logged into the admin panel, there was nothing under the Booking model. This is what the lesson_details.html looks like. This is what it looks like with the booking modal open. Models.py from django.db import models from django.contrib.auth.models import User from cloudinary.models import CloudinaryField STATUS = ((0, "Draft"), (1, "Published")) class Coach(models.Model): RECREATIONAL = 'recreational' FREESTYLE = 'freestyle' DANCE = 'dance' PAIRS = 'pairs' SPECIALIZATION_CHOICES = [ (RECREATIONAL, 'Recreational'), (FREESTYLE, 'Freestyle'), (DANCE, 'Dance'), (PAIRS, 'Pairs'), ] first_name = models.CharField(max_length=80) last_name = models.CharField(max_length=80) email = models.EmailField(max_length=100) bio = models.CharField(max_length=140, help_text="Enter a brief bio") image = CloudinaryField('image', default='placeholder', help_text="Image must be a square") specialization = models.CharField(max_length=20, choices=SPECIALIZATION_CHOICES, default=RECREATIONAL) years_of_experience = models.PositiveIntegerField(default='1', help_text="Enter a positive integer.") status = models.IntegerField(choices=STATUS, default=0) class Meta: ordering = ['pk'] def __str__(self): return f'Coach {self.first_name} {self.last_name}' class Lesson(models.Model): # code from https://adamj.eu/tech/2020/01/27/moving-to-django-3-field-choices-enumeration-types/ BEGINNER = 'beginner' INTERMEDIATE = 'intermediate' ADVANCED = 'advanced' LEVEL_CHOICES = [ (BEGINNER, 'Beginner'), (INTERMEDIATE, 'Intermediate'), (ADVANCED, 'Advanced'), ] title = models.CharField(max_length=100, unique=True) … -
using queryset in forms django
hi My friends, I want to show only the professors of the same branch in the form, but it is not possible forms.py class ClassesForm(forms.ModelForm): class Meta: model = Classes fields = [ 'sath', 'code', 'name', 'gender', 'teacher', 'meeting', 'holding', 'teadadjalasat', 'sen', 'datestart', 'miantermstart', 'dateend', 'description', 'room', ] def __init__(self, *args, **kwargs): super(ClassesForm, self).__init__(*args, **kwargs) self.fields['teacher'].queryset = Profile.objects.filter(semat__icontains="teacher", status=1,branch=request.user.branch) NameError at /operation/classes/create/ name 'request' is not defined vlews.py class classesCreate(ClassesInline, CreateView): def get_context_data(self, **kwargs): ctx = super(classesCreate, self).get_context_data(**kwargs) ctx['named_formsets'] = self.get_named_formsets() return ctx def get_named_formsets(self): if self.request.method == "GET": return { 'reservs': ReservationFormSet(prefix='reservs'), } else: return { 'reservs': ReservationFormSet(self.request.POST or None, self.request.FILES or None, prefix='reservs'), }