Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to connect databricks delta tables from Django application
I am new to Django framework, in my project I have requirement that I have to connect to databricks delta tables and perform CRUD operation on it. If we can connect it. I request you to list down the steps please.Thanks. -
Efficient way to continuously consume messages from Redis Streams while being connected to Websockets through Django Channels
I have written a Django application to receive updates of long running tasks. I am using Redis as a channel layer for web-sockets and also making use of Redis Streams to store the updates of the tasks that are currently running. I have spawned a thread from connect method of WebSocket Consumer to run an infinite loop to continuously check for updates from Redis Consumer. This seems to be a hackish solution for what I am trying to achieve i.e. to remain connected to the websocket and also simultaneously receive updates from Redis Streams. This is my code for Websocket Consumer. As you can see, I am running an infinite loop to check for any new messages in the stream through Redis Consumer. import json from threading import Thread from asgiref.sync import async_to_sync from channels.generic.websocket import WebsocketConsumer from django.utils import timezone from redis import ConnectionPool, Redis from redis_streams.consumer import Consumer class ProgressStateConsumer(WebsocketConsumer): def __init__(self): self.task_id = self.task_group_name = None connection_pool = ConnectionPool( host="localhost", port=6379, db=0, decode_responses=True, ) self.redis_connection = Redis(connection_pool=connection_pool) self.messages = [] super().__init__() def connect(self): task_id = self.scope["url_route"]["kwargs"]["task_id"] self.task_id = task_id self.stream = f"task:{self.task_id}" self.task_group_name = ( f"task-{self.task_id}-{round(timezone.now().timestamp())}" ) async_to_sync(self.channel_layer.group_add)( self.task_group_name, self.channel_name ) thread = Thread(target=self.send_status) thread.start() self.accept() def … -
How can I get index of list in django template
I have 3 list item1,item2,item3 views.py context={'item0': region.objects.all(), 'item1': [1,2,3,4,5,6,7,8,9,10], 'item2': ['one', 'two','three','four', 'five'], 'item3': ['six', 'seven','eight','nine','ten'], 'item4': "test", 'item5': 5, 'item6': range(5), } return render(request, 'btscreate.html', context ) I tried get in template 1) {% for num in item1 %} <td> {{ num }} </td> # this work <td> {{ how can I get values item2 and item3 ? }} </td> {% endfor %} {% for num in item6 %} <td> {{ item2.0 }} </td> # that work <td> {{ item2.num }} </td> # but that doesn't work {% endfor %} how can I get values item2 and item3 ? -
django-channels - group send does not call the function defined in "type"
I have this Consumer: class TableConsumer(AsyncWebsocketConsumer): async def connect(self): self.table_name = f'table_test' self.channel_name = f'channel_test' await self.accept() await self.channel_layer.group_add( self.table_name, self.channel_name ) await self.manage_new_game_video() async def manage_new_game_video(self): await self.channel_layer.group_send( self.table_name, {"type": "chat_message", "message": "message"} ) # Receive message from room group async def chat_message(self, event): print("test") message = event["message"] # Send message to WebSocket await self.send(text_data=json.dumps({"message": message})) for some reason, the print statement is never executed and I don't understand why. Why can that happen? Thanks. -
Django Could not parse the remainder: ',' from 'previous
Help is needed. I have tried many solutions, but nothing works. Always one mistake. Please help me solve the problem. TemplateSyntaxError Could not parse the remainder: ',' from 'previous_episode.seasonpost.slug,' previous return render(request, 'content/episode.html', { … Local vars current_episode <episode: episode-2> episodepost <QuerySet [<episode: episode-2>]> episodepost_slug 'episode-2' next_episode <episode: episode-3> previous_episode <episode: episode-1> request <WSGIRequest: GET '/seasons/season-1/episode-2'> seasonpost_slug 'season-1' Models class home(models.Model): slug = models.SlugField(max_length=266, unique=True, db_index=True, verbose_name=('SLUG')) ... def __str__(self): return self.slug class seasons(models.Model): slug = models.SlugField(max_length=266, unique=True, db_index=True, verbose_name=('SLUG')) ... def __str__(self): return self.slug class season(models.Model): slug = models.SlugField(max_length=266, unique=True, db_index=True, verbose_name=('SLUG')) ... def __str__(self): return self.slug def get_absolute_url(self): return reverse('seasonpost', kwargs={'seasonpost_slug': self.slug, 'episodepost_slug': self.slug}) class episode(models.Model): slug = models.SlugField(max_length=266, unique=True, db_index=True, verbose_name=('SLUG')) ... cat = models.ForeignKey('season', on_delete=models.PROTECT, null=True) def __str__(self): return self.slug def get_absolute_url(self): return reverse('episodepost', kwargs={'seasonpost_slug': self.slug, 'episodepost_slug': self.slug}) Views def ContentHome(request): homepages=home.objects.all() season_menu=season.objects.all() seasonpages=season.objects.all() return render(request, 'content/home.html',{ 'season_menu':season_menu, 'home':homepages, 'season':seasonpages}) def ContentSeasons(request): seasonspages=seasons.objects.all() homepages=home.objects.all() season_menu=season.objects.all() seasonpages=season.objects.all() return render(request, 'content/seasons.html',{ 'season_menu':season_menu, 'home':homepages, 'seasons':seasonspages, 'season':seasonpages}) def ContentSeason(request, seasonpost_slug): seasonpages = get_list_or_404(season, slug=seasonpost_slug) homepages=home.objects.all() seasonspages=seasons.objects.all() season_menu=season.objects.all() episodepost = episode.objects.filter() seasonpages=season.objects.filter(slug=seasonpost_slug) return render(request, 'content/season.html',{ 'home':homepages, 'seasons':seasonspages, 'season':seasonpages, 'season_menu':season_menu, 'episode': episodepost,}) def ContentEpisode(request, seasonpost_slug, episodepost_slug): episodepost = episode.objects.filter(slug=episodepost_slug, cat__slug=seasonpost_slug) current_episode = get_object_or_404(episodepost, slug=episodepost_slug, cat__slug=seasonpost_slug) previous_episode = episode.objects.filter(cat__slug=seasonpost_slug, pk__lt=current_episode.pk).first() next_episode = episode.objects.filter(cat__slug=seasonpost_slug, … -
How to re-deploy Django changes in linux
My application is up and running on my server. I'm using linux Nginx and Gunicorn. I'm logging in to the server using ssh with private key. My question is how do I re-deploy updated version of the application? My first attempt was cloning the project from my git repository into a directory on my server. Cloning it again doesn't seem like a good option. -
The row in table 'owl_course' with primary key '1' has an invalid foreign key
The total error is raise IntegrityError( django.db.utils.IntegrityError: The row in table 'owl_course' with primary key '1' has an invalid foreign key: owl_course.subject_id contains a value 'math' that does not have a corresponding value in owl_subject.id. I have a model Course: class Course(models.Model): id = models.CharField(max_length=7, primary_key=True) name = models.CharField(max_length=16, default="") teacher = models.ForeignKey(Teacher, on_delete=models.SET_NULL, null=True) students = models.ManyToManyField(Student) staff = models.ForeignKey(Staff, on_delete=models.SET_NULL, null=True) startDate = models.DateTimeField(blank=True, null = True) endDate = models.DateTimeField(blank=True, null = True) student_number = models.IntegerField(_("student_number"), blank=True, default=0) subject= models.CharField(max_length=14, default = "") Originally, the attribute subject is just a Charfield. But later I changed it into a foregin key. school =models.ForeignKey(School, on_delete = models.SET_NULL, null=True); And then I run migration and migrate. But the stupid error msg pop out. And error can't be fixed even I change fiedl back to Charfield. Why django orm works so stupid? How can I address this? -
Django: Is it a good idea to have two caches on one memcached instance?
I would like to have two caches with different timeouts on one memcached instance in my django 3 instance: CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache', 'LOCATION': '127.0.0.1:11211', 'CACHE_KEY_PREFIX': 'default_cache', 'TIMEOUT': 300, }, 'custom': { 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache', 'LOCATION': '127.0.0.1:11211', 'CACHE_KEY_PREFIX': 'custom_cache', 'TIMEOUT': 3600 * 24, }, } I did not find an example which does this, so I`m not sure if something could go wrong with this. What do you think? Could there e.g. be a problem with django["cachename"].clear() command? -
proper way to import django base settings in production settings
I have seen alot of articles and videos about the best practices when it comes to managing django settings file. And almost of them talks about having a base settings base_settings.py and then environment settings, like development_settings.py, production_settings.py etc. usually in the dev and prod settings the base setting is imported into it like from project.settings.base import * I have also read that import * is a bad practice, so the question is WHAT IS THE RIGHT WAY TO IMPORT THE SETTINGS WITHOUT MESSING UP THE NAMESPACE. One of the warnings I get when running my test with pytest is the namespace warning, which I presume come from the * import see warning below when I run pytest ..\..\..\..\Miniconda3\envs\salary\Lib\site-packages\pkg_resources\__init__.py:2804 C:\Users\seven\Miniconda3\envs\salary\Lib\site-packages\pkg_resources\__init__.py:2804: DeprecationWarning: Deprecated call to `pkg_resources.declare_namespace('ruamel')`. Implementing implicit namespace packages (as specified in PEP 420) is preferred to `pkg_resources.declare_namespace`. See https://setuptools.pypa.io/en/latest/references/keywords.html#keyword-namespace-packages declare_namespace(pkg) ..\..\..\..\Miniconda3\envs\salary\Lib\site-packages\pkg_resources\__init__.py:2804 ..\..\..\..\Miniconda3\envs\salary\Lib\site-packages\pkg_resources\__init__.py:2804 C:\Users\seven\Miniconda3\envs\salary\Lib\site-packages\pkg_resources\__init__.py:2804: DeprecationWarning: Deprecated call to `pkg_resources.declare_namespace('zope')`. Implementing implicit namespace packages (as specified in PEP 420) is preferred to `pkg_resources.declare_namespace`. See https://setuptools.pypa.io/en/latest/references/keywords.html#keyword-namespace-packages declare_namespace(pkg) ..\..\..\..\Miniconda3\envs\salary\Lib\site-packages\coreapi\codecs\download.py:5 C:\Users\seven\Miniconda3\envs\salary\Lib\site-packages\coreapi\codecs\download.py:5: DeprecationWarning: 'cgi' is deprecated and slated for removal in Python 3.13 import cgi -- Docs: https://docs.pytest.org/en/stable/how-to/capture-warnings.html I don't exactly know what is raising these warnings but it goes away when I remove the … -
django strawberry query choice field values
I am using strawberry graphql for my project. I have a form field where I need to show options from my choice fields. I have a model like class Product(models.Model): REQUIREMENT_CHOICES = ( ("N", "New"), ("O", "Old"), ("M", "Maintained"), ) requirement = models.CharField( max_length=50, choices=REQUIREMENT_CHOICES, blank=True, ) Here in my graphql query how can I query REQUIREMENT_CHOICES without without making custom query to handle this. django-graphene would give options query easily. How could I do this in strawberry ? -
setting up Celery with RabbitMQ
I'm trying to set up Celery (5.2.7) with RabbitMQ (3.8.19) (Django 4.1.5) As a result, the task appears in the “celery” queue with the “Unacked” status, and after 30 minutes it goes into the “Ready” status with a message. "amqp.exceptions.PreconditionFailed: (0, 0): (406) PRECONDITION_FAILED - delivery acknowledgement on channel 1 timed out. Timeout value used: 1800000 ms. This timeout value can be configured, see consumers doc guide to learn more" When calling the method directly (without .delay), everything works correctly. I have no idea what is configured incorrectly running celery: $ celery -A mylocal worker -l info -------------- celery@DEV2 v5.2.7 (dawn-chorus) --- ***** ----- -- ******* ---- Windows-1 - *** --- * --- - ** ---------- [config] - ** ---------- .> app: mylocal:0x18205ade830 - ** ---------- .> transport: amqp://<RMQLogin>:**@<RMQ_HOST>:<RMQ_PORT>/<RMQ_VIRTUAL_HOST> - ** ---------- .> results: disabled:// - *** --- * --- .> concurrency: 12 (prefork) -- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker) --- ***** ----- -------------- [queues] .> celery exchange=celery(direct) key=celery [tasks] . myapp.tasks.send_spam_email Project structure: mylocal | -mylocal | - init.py - celery.py - settings.py -myapp | - templates | - myapp | - celery.html - admin.py - forms.py - models.py - … -
How to fix pg_dump: error: server version: 14.2; pg_dump version: 13.9 (Debian 13.9-0+deb11u1), but my db service can't down version
I use dbbackup. When I call python manage.py dbbackup I have error: Traceback (most recent call last): File "/app/manage.py", line 22, in <module> main() File "/app/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/opt/venv_vsm/lib/python3.9/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/opt/venv_vsm/lib/python3.9/site-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/opt/venv_vsm/lib/python3.9/site-packages/django/core/management/base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "/opt/venv_vsm/lib/python3.9/site-packages/django/core/management/base.py", line 398, in execute output = self.handle(*args, **options) File "/opt/venv_vsm/lib/python3.9/site-packages/dbbackup/utils.py", line 118, in wrapper func(*args, **kwargs) File "/opt/venv_vsm/lib/python3.9/site-packages/dbbackup/management/commands/dbbackup.py", line 61, in handle self._save_new_backup(database) File "/opt/venv_vsm/lib/python3.9/site-packages/dbbackup/management/commands/dbbackup.py", line 74, in _save_new_backup outputfile = self.connector.create_dump() File "/opt/venv_vsm/lib/python3.9/site-packages/dbbackup/db/base.py", line 78, in create_dump dump = self._create_dump() File "/opt/venv_vsm/lib/python3.9/site-packages/dbbackup/db/postgresql.py", line 38, in _create_dump stdout, stderr = self.run_command(cmd, env=self.dump_env) File "/opt/venv_vsm/lib/python3.9/site-packages/dbbackup/db/postgresql.py", line 21, in run_command return super(PgDumpConnector, self).run_command(*args, **kwargs) File "/opt/venv_vsm/lib/python3.9/site-packages/dbbackup/db/base.py", line 150, in run_command raise exceptions.CommandConnectorError( dbbackup.db.exceptions.CommandConnectorError: Error running: pg_dump --host=db --port=5432 --username=postgres --no-password --clean postgres pg_dump: error: server version: 14.2; pg_dump version: 13.9 (Debian 13.9-0+deb11u1) pg_dump: error: aborting because of server version mismatch I understand that: my service use postgres 14.2 and my client use postgres 13. But I can't downgrade my service version, and my client just install version 13.9 (it is hightest) -
How do I embed a QR scanner pop-out upon clicking the QR camera icon?
I am trying to get a UI dialog window to display a QR code scanner upon clicking on the icon button for that corresponding row. Currently, when I click on the icon, nothing happens. I am unsure of how to display the QR scanner in the form of a dialog box. I am relatively new to element-ui and would greatly appreciate any inputs. {% block mainbody %} {% verbatim %} <div id="app2" class="container"> <div class="emr-table"> <el-table ref="multipleTable" :data="list" stripe style="width: 50%" @row-click="handle" @selection-change="handleSelectionChange"> <el-table-column prop="id" label="Index"> </el-table-column> <el-table-column prop="order_id" label="Order ID"> </el-table-column> <el-table-column prop="ward_number" label="Ward No."> </el-table-column> <el-table-column prop="qr" label="QR"> <template slot-scope="scope"> <el-button size="mini" type="warning" icon="el-icon-camera" circle @click="launchQR(scope.row)"> </el-button> </template> </el-table-column> </el-table> </div> </div> {% endverbatim %} <script> new Vue({ el: '#app2', data() { return { list: [] } }, mounted() { this.getemrList() }, methods: { getemrList() { // Obtain EMR list axios.post(ToDJ('emrList'), new URLSearchParams()).then(res => { if (res.data.code === 0) { console.log(res.data.data) this.list = res.data.data } else { this.NotifyFail(res.data.data) } }) }, // Success notification NotifySuc(str) { this.$message({ message: str, type: 'success' }) }, // Error notification NotifyFail(str) { this.$message({ message: str, type: 'warning' }) } } }) </script> {% endblock %} -
Django rest framework, AttributeError: 'str' object has no attribute 'data' and unable to upload image using forms
I'm struggling with recruitment task, i'm pretty new in Django and I haven't used rest framework before. I'm trying to built view where user can upload picture and set how long link should be valid(in range 3000-30000, validation works for that). This feature works thru postman instaed of received link to file I have following error: return renderer.render(serializer.data, None, {'style': style}) AttributeError: 'str' object has no attribute 'data' When I try to upload file using website serializer is not passing validation. I'm using render_form in html file and result in QueryDict is different than in postman so i guess thats the issue, however no idea how to solve it: using website: 'image_url': ['airplane.jpg'], using postman: 'image_url': [<InMemoryUploadedFile: airplane.jpg (image/jpeg)>] models.py: import datetime from django.db import models from django.contrib.auth.models import User from images.validators import expiring_in_validator def upload_to(instance, filename): unique_identify = str(int(datetime.datetime.now().timestamp())) return f"media/{filename}-{unique_identify}" # Create your models here. class Image(models.Model): uploaded_by = models.ForeignKey(User, on_delete=models.CASCADE) image_url = models.ImageField(upload_to=upload_to) expiring_within = models.IntegerField(validators=[expiring_in_validator]) serializers.py: from rest_framework import serializers from images.models import Image class PostSerializer(serializers.ModelSerializer): class Meta: model = Image fields = ['image_url', 'expiring_within'] views.py: from django.shortcuts import render from django.views import View from rest_framework import status from rest_framework.parsers import FormParser, MultiPartParser from rest_framework.permissions import … -
How to implement login with Axios for multiple types of users?
I am building a web application ( with VueJs) that allows multiple types of users to login (e.g., regular users and administrators). I am using Axios to handle HTTP requests, but I am not sure how to implement login for multiple types of users. Certainly, here is the code with the provided section added to it: async submitForm() { const formData = { email: this.email, password: this.password } axios.defaults.headers.common["Authorization"] = ""; localStorage.removeItem("token"); await axios .post('http://127.0.0.1:8000/login', formData) .then(response => { console.log('response :', response.data) const token = response.data.auth_token this.$store.commit('setToken', token); axios.defaults.headers.common["Authorization"] = "Token " + token; localStorage.setItem('token', token); const toPath = this.$route.query.to || '/admin'; this.$router.push(toPath); }) .catch(error => { if (error.response) { for(const property in error.response.data) { this.errors.push(`${property}: ${error.response.data[property]}`); } } else { this.errors.push('Something went wrong. Please try again'); console.log(JSON.stringify(error.response.data)); } console.log(this.errors); }) }, Can someone provide guidance on how to achieve this with Axios? Any examples or code snippets would be greatly appreciated. Thank you! -
'Search' object has no attribute 'get'
I'm trying to create a search by last name, but it gives an error. Maybe I'm not comparing something correctly or taking the wrong value? forms.py from django import forms class CouponApplyForm(forms.Form): code = forms.CharField() views.py class Search(Coupon): def get_queryset(self): return Coupon.objects.order_by(fio=self.request.fio.get('q')) def get_context_date(self, *args, **kwargs): context = super().get_context_date(*args, **kwargs) context["q"]=self.request.GET.get("q") return context(context, "main/coupons.html") coupons.html <form action="{% url 'search' %}" method="get" class="form-control me-2"> <input type="search" placeholder="1" name="q" class="form-control me-2" required=""> <button type="submit" class="btn1 btn"> <span class="fa fa-search" aria-hidden="true"></span> </button> </form> I can’t understand, I display the search by last name, compare it with the request and give an error -
Why django-rest-framework-simplejwt integrated with my existing code is accepting uuid instead of username? [closed]
I am trying to integrate djangorestframework-simplejwt module in my existing Django project according to official document. The APIs is published but the fields its accepting is uuid and password instead of username and password. Although, I am passing the correct uuid and password but the api is not working by not authenticating and giving back JWT token. Versions I am using: django 3.2.12 djangorestframework 3.13.1 djangorestframework-simplejwt 5.2.2 Swagger view of token api: The user model: -
Why form return error "inactive user" in generic.View
I am writing a site on Django and faced the problem that when users are authorized, the form returns the error "This user account is inactive" in any case. Although I did this before and everything was fine This is my views.py file: template_name = 'users_logic/user_login.html' form_class = UserLoginForm success_url = reverse_lazy('main_page') def get(self, request): form = self.form_class return render(request, 'users_logic/user_login.html', {'form': form}) def post(self, request): form = self.form_class(request.POST) if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') user = authenticate(username=username, password=password, backend=settings.AUTHENTICATION_BACKEND) print(user) if user is not None: login(request, user) print(user) messages.success(request, 'Ви успішно авторизувались') return redirect('main_page') else: messages.error(request, 'Помилка авторизації') else: messages.error(request, 'Неправильний логін або пароль') print(form.error_messages) form = self.form_class() return render(request, 'users_logic/user_login.html', {'form': form}) this is my register view: class SignUp(generic.CreateView): template_name = 'users_logic/user_register.html' form_class = UserRegisterForm success_url = reverse_lazy('user_login') success_message = "Реєстрація пройшла успішно" my login_form: class UserLoginForm(AuthenticationForm): class Meta: model = user_form fields = ('username', 'password1') username = forms.CharField(label='Ваш логін', widget=forms.TextInput(attrs={'class': 'form-control'})) password = forms.CharField(label='Ваш пароль', widget=forms.PasswordInput(attrs={'class': 'form-control'})) How can it be fixed? -
Django model admin hooks order
I am trying to find the model admin hooks ordering for a request, I need to inject a LogEntry into an inline model and I am tring to find the correct hook points for addition, modified and delete actions on the form. I know that the log will be created under the modelAdmin in which the inline sits but I need to add one. Is there any documenttation on the modelAdmin hook paths ? Thanks -
Django book details with different form and html template
i have some question about a DJANGO framework book blog details example .My problem is i have a book list in Django template using something like this {% url 'book_details' value.slug_title %}.My problem is for different book details i have a different Django form and different HTML template .i build a snippet code and work fine ,but i dont like this code way ,i would like to propose a different code way to take correct results. here the code : def blog_details(request,slug): data = get_object_or_404(app_descript, slug_title=slug) if str(data.title) == 'name 1': if request.method=='POST': ....................... return render(request, 'details/name1.html', {'data': data}) elif str(data.title) == 'name 2': if request.method=='POST': ............................... return render(request, 'details/name2.html', {'data': data}) elif str(data.title) == 'name 3': if request.method=='POST': ................. return render(request, 'details/name3.html', {'data': data}) -
Optimize Django query in reverse lookup
I have 2 models class Chassis(models.Model): number = models.CharField(max_length=10, unique=True) class Eir(models.Model): chassis = models.ForeignKey( 'management.Chassis', null=True, blank=True, related_name='eir', on_delete=models.SET_NULL ) number = models.IntegerField(unique=True, default=0) I tested via Django CLI >>> chassis = Chassis.objects.prefetch_related('eir') >>> chassis >>> chassis.first().eir.all() I tried the commands above and it still did a query with the eir table as shown below: # produced from ">>> chassis" {"Time":[2023-03-07 08:25:42 UTC], Host:10.116.1.165} LOG: duration: 0.238 ms statement: SELECT "management_chassis"."id", "management_chassis"."number" FROM "management_chassis" LIMIT 21 {"Time":[2023-03-07 08:25:42 UTC], Host:10.116.1.165} LOG: duration: 0.777 ms statement: SELECT "rental_eir"."id", "rental_eir"."number", "rental_eir"."chassis_id" FROM "rental_eir" WHERE "rental_eir"."chassis_id" IN (1292, 104) # produced from ">>> chassis.first().eir.all()" {"Time":[2023-03-07 08:25:59 UTC], Host:10.116.1.165} LOG: duration: 0.239 ms statement: SELECT "rental_eir"."id", "rental_eir"."number", "rental_eir"."chassis_id" FROM "rental_eir" WHERE "rental_eir"."chassis_id" IN (80) I was expecting that there will be no 3rd query anymore as the data will be stored in memory. My real purpose is related to Django REST Framework manipulating the returned data in def to_representation where a reverse lookup is done like ret['eir'] = instance.eir.all().last().id where instance is Chassis model -
Django API file name issue
When i tried to upload a file with filename in arabic , in database it stored as the arabic filename .But when the API calls, the filename '%D8%B3%D8%A7%D9%82_%D8%A7%D9%84%D8%A8%D8%A7%D9%85%D8%A8%D9%88_UP8kxN2.pdf' like this . Can anyone know how to solve the issue? I want to get the filename as Arabic text of filename, -
how to merge to query sets with using keyword values
I am get two query sets, users: {{'username': 'muthu12', 'user id': 25, 'code': 'GKUPDY'} and multiple dict} , 2) deposit history: {{'amount': 16.0, 'user_id':25} and multiple dict..} My expected answer below type of queryset, users = {'username': 'muthu12', 'user_id': 25, 'referrel_code': 'GKUPDY', 'amount': 16,'date_joined': datetime.datetime(2023, 3, 2, 8, 47, 6, 582087)} -
I'm trying to apply css style file but Django not recognizing it
this is the base.html <!DOCTYPE html> {%load static%} <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>{% block page_title %}my challenges{% endblock %}</title> <link rel="stylesheet" href="{% static "style.css"%}"> {%block css_files%} {%endblock%} </head> <body> {% block content %} {% endblock %} </body> </html> challenges.css ul{ list-style: circle; margin: 2rem auto; width: 90% ; max-width: 50rem; box-shadow: 0 2px 8px rgba(0, 0, 0, 0.26); padding: 1rem; border-radius: 1px; } index.html {% extends 'base.html' %} {% load static %} {%block css_files%} <link rel="stylesheet" href="{% static "challenges/challenges.css" %}"> {%endblock%} {%block page_title%} All chalenges {%endblock%} {%block content%} {% include "challenges/includes/header.html" %} <ul> {% for month in months%} <li><a href="{% url "month-challenge" month %}">{{month|title}}</a></li> {% endfor %} </ul> {%endblock%} [path is here in the image[][1]][1] [1]: https://i.stack.imgur.com/2qqmC.png [see the image styles are not applying ][2] [2]: https://i.stack.imgur.com/h9agu.png please help me on this I've already added the path and everything on setting.py also STATIC_URL = "static/" STATICFILES_DIRS = [ BASE_DIR / "static" ] -
how can I merge grpc client and http request?
I want to merge http request and grpc client that means: I have a request for create some object. my service is gateway that means it sends data in celery task and grpc client sends a request and receive stream responses. when should i run this client? should i run the client in same function that sends data in celery task or not? I am really confused.