Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Accessing Uploaded files in Django
I am trying to display the urls of Multiple files I uploaded related to the post model. My settings.py is well set up and the files gets uploaded to the target directory. How can I access the urls of these files and print them on the post details page? This is because I want an individual to be able to download these files. So far I have tried the following. # models.py class Post(RandomIDModel): student = models.ForeignKey(User, on_delete=models.CASCADE) subject = models.CharField(null=True, blank=False, max_length=50) deadline = models.DateTimeField(null=True, blank=False) description = models.TextField(null=True, blank=False) pages = models.IntegerField( validators=[MinValueValidator(1)], default=1,null=True, blank=False) status = models.CharField(max_length=10, choices=status_choices, default="pending") price = models.DecimalField(max_digits=10,decimal_places=2, default=0.00) reference_style = models.CharField( max_length=10, choices=reference_styles, default="Apa" ) number_of_references = models.IntegerField( validators=[MinValueValidator(1)], default=1,null=True, blank=False ) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return str(self.subject) # New form multiple file upload class. class PostAttachment(models.Model): attachment = models.FileField(upload_to="atlogin", blank=True, null=True) post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name="attachment") #views.py @login_required(login_url="/account_login") # @permission_required("main.add_post", login_url="/account_login", raise_exception=True) def create_post(request): if request.method == "POST": form = PostForm(request.POST) attachment_form = PostAttachmentForm(request.POST, request.FILES) attachments = request.FILES.getlist("attachment") if form.is_valid() and attachment_form.is_valid(): post = form.save(commit=False) post.student = request.user post.save() for f in attachments: post_attachment = PostAttachment(attachment=f, post=post) post_attachment.save() messages.success(request, "Upload Succeessful!") return redirect("/dashboard") else: form = PostForm() … -
css file not worked in VScod in Django project
I have a Django project , and I want to have a css file in templates folder . but for examples when I write 'myfirst.css' , The VScode not worked. enter image description here -
How to filter choices in django admin?
I want to create two combo boxes in my Django admin. First one is brand of object and second one is the model of that brand , when i select brand in first combo box, i want second one to get update. -
distinction about txt file and pdf file
I have a django application and a upload method. And A textarea where the content of the file will be returned. So if there is a text file uploaded. Then in the textarea the content of the textfile will be visible. I try it now also with a image in a pdf file. And I try it with a console app. And that works. Tha text in the pdf file will be extracted. But I try it now with the general upload method. And then I get this errror: TypeError at / image must be a wand.image.Image instance, not <UploadFile: UploadFile object (45)> Request Method: POST Request URL: http://127.0.0.1:8000/ Django Version: 4.1.1 Exception Type: TypeError Exception Value: image must be a wand.image.Image instance, not <UploadFile: UploadFile object (45)> Exception Location: C:\Python310\lib\site-packages\wand\image.py, line 9310, in __init__ Raised during: main.views.ReadingFile Python Executable: C:\Python310\python.exe Python Version: 3.10.6 So this is the complete method: from django.shortcuts import render from django.views import View from django.http import HttpResponseRedirect from .forms import ProfileForm from .models import UploadFile from .textFromImages import TextFromImage from wand.image import Image as wi from PIL import Image import pytesseract from django.conf import settings import io import os class ReadingFile(View): def get(self, request): form … -
How to fix error when sending mail with django in docker container? (Cannot assign requested address)
I'm getting an error when sending a letter both in Celery, as in the shell itself. Without the docker itself, there is no such error on the local computer, but there is on the server. Error: send_mail('test', 'test msg', 'volkodav2312@bk.ru', ['volkodav2312@inbox.ru']) Traceback (most recent call last): File "<console>", line 1, in <module> File "/usr/local/lib/python3.10/site-packages/django/core/mail/__init__.py", line 87, in send_mail return mail.send() File "/usr/local/lib/python3.10/site-packages/django/core/mail/message.py", line 298, in send return self.get_connection(fail_silently).send_messages([self]) File "/usr/local/lib/python3.10/site-packages/django/core/mail/backends/smtp.py", line 124, in send_messages new_conn_created = self.open() File "/usr/local/lib/python3.10/site-packages/django/core/mail/backends/smtp.py", line 80, in open self.connection = self.connection_class( File "/usr/local/lib/python3.10/smtplib.py", line 255, in __init__ (code, msg) = self.connect(host, port) File "/usr/local/lib/python3.10/smtplib.py", line 341, in connect self.sock = self._get_socket(host, port, self.timeout) File "/usr/local/lib/python3.10/smtplib.py", line 312, in _get_socket return socket.create_connection((host, port), timeout, File "/usr/local/lib/python3.10/socket.py", line 845, in create_connection raise err File "/usr/local/lib/python3.10/socket.py", line 833, in create_connection sock.connect(sa) OSError: [Errno 99] Cannot assign requested address I looked through the other answers and didn't find anything helpful. I have a password configured, this error occurs in the docker. -
How to add template directory in django?
I'm getting TemplateDoesNotExist at /task/ error. This is my folder structure for project. This is my taskmate/urls.py: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('task/',include('todolist_app.urls')), path('todolist/',include('todolist_app.urls')), ] This is my todolist_app/urls.py: from django.urls import path #from todolist_app import views from . import views urlpatterns = [ path('', views.todolist, name='todolist'), ] This is my todolist_app/views.py: from django.shortcuts import render from django.http import HttpResponse # Create your views here. def todolist(request): return render(request, 'todolist.html',{}) This is my settings.py(important components) TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [(os.path.join(os.path.dirname(os.path.dirname(__file__)),'todolist_app/templates').replace('\\','/'))],#'DIRS': 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] I'm highly suspicious that the issue I'm getting is due to "DIRS" of template. I have tried couple of different things there, but none seem to have worked. These are what I've tried there: 'DIRS': [os.path.join(BASE_DIR,'templates')], 'DIRS': [os.path.join(os.path.dirname(__file__),'templates').replace('\\','/')],#'DIRS': 'DIRS': [(os.path.join(os.path.dirname(os.path.dirname(__file__)),'todolist_app/templates').replace('\\','/'))],#'DIRS': I've also added "todolist_app" to installed apps. -
Can CreateView show additional rows for every row in a certain FK?
I'm sorry I do not know the correct terminology to describe what I am trying to accomplish briefly, so I am hoping you can read my explanation below. I have even added an image showing the results I want to accomplish. Background + Explanation I'm refactoring a language learning application in preparation to make it Open Source. It focuses on writing and composition. The way it works is that a user can create a Post and that post's text will automatically split into individual sentences via NLP where then each individual sentence will get added to another table called PostRow. In a separate view, a user on the platform is able to make corrections to this post. Then all of the individual corrections get added to the CorrectedRows table. When a user visits the MakeCorrection view to correct a post then the form would essentially do this: Filter all of the PostRows for the Post in question For every filtered PostRow row show the CorrectedRow form too In other words, if the Post's text has 6 sentences, then the MakeCorrection view should show 6 CorrectedRows. Tables class PostRow(SoftDeleteModel, TimeStampedModel): ... post = models.ForeignKey(Post, on_delete=models.CASCADE) sentence = models.TextField() class CorrectedRows(SoftDeleteModel, TimeStampedModel): … -
Django model property field calculated with field from another child model
class BusinessFunction(models.Model): name = models.CharField(max_length=200) priority_rating = models.PositiveIntegerField(null=True, blank=True) location = models.CharField(max_length=200) network_service_related = models.CharField(max_length=200) class Meta: ordering = ['name'] def __str__(self): return self.name class CriticalImpact(models.Model): businessfunction = models.ForeignKey(BusinessFunction, on_delete=models.CASCADE) priority = models.PositiveSmallIntegerField(null=True, blank=True) financial = models.PositiveSmallIntegerField(null=True, blank=True) legal = models.PositiveSmallIntegerField(null=True, blank=True) score = models.PositiveSmallIntegerField(null=True, blank=True) percentage = models.PositiveIntegerField(null=True, blank=True) class Meta: ordering = ['businessfunction'] class TimeImpact(models.Model): businessfunction = models.ForeignKey(BusinessFunction, on_delete=models.CASCADE) impact_score_financial = models.DecimalField(max_digits=5, decimal_places=2, blank=True, null=True) impact_score_asset = models.DecimalField(max_digits=5, decimal_places=2, blank=True, null=True) final_score = models.DecimalField(max_digits=5, decimal_places=2, blank=True, null=True) class Meta: ordering = ['businessfunction'] @property def final_rating(self): final_rating = (self.final_score + ????????)/2 return final_rating I have code as above and would like to add property of final rating using calculation from own table(TimeImpact) field final_score and field from CriticalImpact field ie percentage. The problem is how i can get the field percentage from CriticalImpact table which is the child of business function table. I've searched before but most of the answer is calculated field coming from field in own table and parent table, not with another child table. Appreciate any helps. Thanks -
Could not resolve URL for hyperlinked relationship using view name "user-detail" (from Rest Framework Quickstart)
I am following the tutorial for rest framework. I have no idea this part of the code ain't working when it works for the apigroups. Please tell me what is the underlying issue. Thank you. ERROR: ImproperlyConfigured at /polls/users/ Could not resolve URL for hyperlinked relationship using view name "user-detail". You may have failed to include the related model in your API, or incorrectly configured the `lookup_field` attribute on this field. Serializers: from django.contrib.auth.models import User, Group from rest_framework import serializers class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = ['url', 'username', 'email', 'groups'] class GroupSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Group fields = ['url', 'name'] #Views from django.contrib.auth.models import User, Group from rest_framework import viewsets from rest_framework import permissions from .serializers import UserSerializer, GroupSerializer class UserViewSet(viewsets.ModelViewSet): """ API endpoint that allows users to be viewed or edited """ queryset = User.objects.all().order_by('-date_joined') serializer_class = UserSerializer permission_classes = [permissions.IsAuthenticated] class GroupViewSet(viewsets.ModelViewSet): """ API endpoint that allows groups to be viewed or edited """ queryset = Group.objects.all() serializer_class = GroupSerializer permission_classes = [permissions.IsAuthenticated] #Urls from django.urls import path, include from . import views from rest_framework import routers # for rest framework router = routers.DefaultRouter() router.register(r'users', views.UserViewSet) router.register(r'groups', views.GroupViewSet) urlpatterns = [ path('', include(router.urls)), … -
Celery second unregistered task
I have a doubt regarding the implementation of celery with rabbitMQ since only the first function (debug_task()) that I have defined in celery.py is executed. The problem is that send_user_mail(randomNumber, email) is not working. debug_task is working, so it's registered. This is the celery console [2022-10-08 22:28:48,081: ERROR/MainProcess] Received unregistered task of type 'callservices.celery.send_proveedor_mail_new_orden'. The message has been ignored and discarded. Did you remember to import the module containing this task? Or maybe you are using relative imports? Why it's unregistered? celery.py from __future__ import absolute_import, unicode_literals import os from celery import Celery from django.conf import settings from django.core.mail import EmailMultiAlternatives, send_mail os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'callservices.settings') app = Celery('tasks',broker='pyamqp://guest@localhost//') app.config_from_object('django.conf:settings') app.autodiscover_tasks(settings.INSTALLED_APPS) @app.task() def debug_task(): print("hi all") @app.task() def send_user_mail(randomNumber, email): subject = 'email validation - ServicesYA' cuerpo="Your number is: "+str(randomNumber) send_mail(subject, cuerpo ,'xxx.ssmtp@xxx.com', [email],fail_silently = False) return 1 This is init.py # This will make sure the app is always imported when # Django starts so that shared_task will use this app. from celery import app as celery_app __all__ = ('celery_app',) and in settings.py I add this line: BROKER_URL = "amqp://guest:guest@localhost:5672//" -
How to view multiple images under separate posts in profile page
I am building a social media website. On the profile page and home page are different posts. Each can have multiple images. I created a different model for images and set ForeignKey to Post model. The form for uploading text and images works fine because the images attach to each post in the database. However, I am having issues writing the views code for the page they are to display. I am getting just text with no images. I am trying to add an Id to each post in the views but I have no idea how to do that since they are all in one page and therefore have no separate urls. I don't know if that is the right approach. Help me please. Thanks. -
Suddenly ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable?
Suddenly my Django project showed me the following ImportError: "ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment?". It ran fine before. I work on Mac m1 using PyCharm Professional. My Django is installed. My venv is activated. So, I guess I have problem with PYTHONPATH . My interpreter is exactly I would like to use: Actually I have some versions of Python. which Python shows me: (venv) user_name@computer_name project_name % which python python: aliased to /usr/bin/python3 (venv) user_name@computer_name project_name % which python3 /Users/user_name/PyCharmProjects/TrainingProjects/project_name/venv/bin/python3 (venv) user_name@computer_name project_name % which python3.9 /opt/homebrew/bin/python3.9 python3 -c "import sys; print(sys.path)" shows me: /opt/homebrew/Cellar/python@3.10/3.10.7/Frameworks/Python.framework/Versions/3.10/lib/python310.zip /opt/homebrew/Cellar/python@3.10/3.10.7/Frameworks/Python.framework/Versions/3.10/lib/python3.10 /opt/homebrew/Cellar/python@3.10/3.10.7/Frameworks/Python.framework/Versions/3.10/lib/python3.10/lib-dynload /Users/user_name/PyCharmProjects/TrainingProjects/project_name/venv/lib/python3.10/site-packages If I understand this output correctly, it means that there is no python 3.9 in my PYTHONPATH for now. In my settings.py, there are: import os import sys #not active from pathlib import Path BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) which $PYTHONPATH brings me PYTHONPATH not found. echo $PYTHONPATH brings me nothing. The export: export PYTHONPATH=$PYTHONPATH:/Library/Frameworks/Python.framework/Versions/3.9/bin/python3 didn't help. Any help is highly appreciated. -
Django One-To-Two Relation
I want to implement a case where model A has exactly two B instances and model B has exactly one A instance. What is the best way to implement this? class A(Model): b1 = OneToOneField(B) b2 = OneToOneField(B) If I use this I have to provide two different related names to b1 and b2 fields. I want be able to simply say b.a_set.first() and get the object since I know B will have single A. And this is not really oneToTwo I think, b1 and b2 could point to the same B object although this is not critical at the moment. class B(Model): a = ForeignKey(A) If I use this then it is OneToMany, I want to be explicit about relation, and be able to use a.b1 and a.b2. Also I will be accessing model B from model A frequently so this is very inefficient. It doesn't make sense to search through table B when I know there are exactly two related B instances. I should be able to store the corresponding B ids in table A like in the previous case. What would be a good way to implement this? -
Django Autocomplete Light not working with Bootstrap 5 Modal
I am newbie to Python and Django. This is my first post. Sorry if I omit relevant information. I'm using DAL on a form inside a Bootstrap modal. Clicking the dropdown list appears behind the modal. The autocomplete function works correctly if I do it outside of the modal. I'm using: Django: 4.0.5 django-autocomplete-light: 3.9.4 Bootstrap 5.2.2 Python 3.10.4 To try to fix it, I have created a style.css file with the following code, as indicated in: bootstrap modal with select2 z-index .select2-container { z-index: 9999 !important; } Now the list appears in front of the modal, but it doesn't allow typing in the search box. I've tried doing the following, but it doesn't work: https://select2.org/troubleshooting/common-problems $(document).ready(function() { $("#codigo_emplazamiento").select2({ dropdownParent: $("#FormularioCrear") }); }); I've tried removing tabindex="-1" from the modal, but it doesn't work. It seems to be related to this, but I can't get it to work: https://lightrun.com/answers/yourlabs-django-autocomplete-light-search-input-not-receiving-focus I really appreciate your help. Thank you very much. This is my code: forms.py class FormularioTarea(forms.ModelForm): class Meta: model = Tarea fields = ['referencia_interna', 'codigo_emplazamiento', 'estado', 'fecha_fin', 'tipo_documento'] autocomplete.ModelSelect2(url='emplazamientoautocompletar')}) widgets = { 'codigo_emplazamiento': autocomplete.Select2( url='emplazamientoautocompletar', ) } models.py class Emplazamiento(models.Model): TIPO_ELECCION = (('URB', 'Urbano'), ('RUR', 'Rural')) codigo_emplazamiento = models.CharField(unique=True, max_length=10) direccion … -
Django on phones and other recommendations
I am trying to run django and run it's virtualenv on pycharm, is there a better python IDE to run django on phones or how I can do it on pycharm? -
KeyError: "Got KeyError when attempting to get a value for field `password` on serializer `LoginSerializer`
I have a login view that looks like this but I keep getting a KeyError whenever I access the API. I cannot seem to fix with the related answers. class LoginAPIView(GenericAPIView): serializer_class = LoginSerializer def post(self, request): serializer = self.serializer_class(data=request.data) serializer.is_valid(raise_exception=True) return Response(serializer.data, status=status.HTTP_200_OK) The serializer looks like this: class LoginSerializer(serializers.ModelSerializer): email = serializers.EmailField() password = serializers.CharField(min_length=6) username = serializers.CharField(read_only=True) tokens = serializers.CharField(read_only=True) class Meta: model = User fields = ["email", "password", "username", "tokens"] def validate(self, attrs): email = attrs.get("email", "") password = attrs.get("password", "") user = auth.authenticate(email=email, password=password) if not user: raise AuthenticationFailed("Invalid credentials") if not user.is_active: raise AuthenticationFailed("Account is not active, please contact admin") return { "email": user.email, "username": user.username, "tokens": user.tokens(), } when I access this endpoint, I get this error: KeyError: "Got KeyError when attempting to get a value for field `password` on serializer `LoginSerializer`.\nThe serializer field might be named incorrectly and not match any attribute or key on the `dict` instance.\nOriginal exception text was: 'password'." full error below. [08/Oct/2022 23:29:57] "POST /auth/register/ HTTP/1.1" 201 54 Internal Server Error: /auth/login/ Traceback (most recent call last): File "/home/xorlali/.cache/pypoetry/virtualenvs/refive-backend-0hCIKWkR-py3.9/lib/python3.9/site-packages/rest_framework/fields.py", line 446, in get_attribute return get_attribute(instance, self.source_attrs) File "/home/xorlali/.cache/pypoetry/virtualenvs/refive-backend-0hCIKWkR-py3.9/lib/python3.9/site-packages/rest_framework/fields.py", line 94, in get_attribute instance = instance[attr] KeyError: 'password' During … -
I have installed MySQL for Python . Now I try to connect to the MySQL Community Server on my local machine, using this code:
DATABASES = { 'default': { 'NAME': "food", 'ENGINE': 'django.db.backends.mysql', 'HOST': 'localhost', 'USER': 'root', 'PASSWORD': 'groot', This code fails with this error: ... connection = Database.connect(**conn_params) File "C:\Users\mona\Downloads\food-ordering-system-master\food-ordering-system-master\food-ordering-system\env\lib\site-packages\MySQLdb_init_.py", line 84, in Connect return Connection(*args, **kwargs) File "C:\Users\mona\Downloads\food-ordering-system-master\food-ordering-system-master\food-ordering-system\env\lib\site-packages\MySQLdb\connections.py", line 179, in init super(Connection, self).init(*args, **kwargs2) django.db.utils.OperationalError: (2002, "Can't connect to MySQL server on 'localhost' (10061)") -
Why Is Ajax Creating a New Comment When I'm Trying To Edit An Existing One?
I am trying to do a Django Blog in Class Based Views. They're proving very difficult to me anyway. I feel like I'm pretty close...I suspect it's creating a new one because I'm combining DetailView and trying to include an UpdateView in my page. I'm overriding POST on the DetailView...and perhaps that's why when I try to do my Update of the comment the overriden Post on DetailView is overriding that action? Here's my code.... HTML... <!DOCTYPE html> <form method='POST' class="comment-form"> {% csrf_token %} <div class="spacer284"> {{ form.comment }} </div> <button class="button7" type="submit">Submit</button> </form> <div class="spacer285"> {% include 'suggestion_comments.html' %} </div> </div> {% endblock %} Note that I'm doing an include so that I can loop through the comments more easily... Here's the include template... {% if suggestion_comments %} <h2>Comments</h2> {% for comment in object.suggestion_comments.all %} <div class="spacer291"> <p><a href="{% url 'Main:associate_directory_associate_detail' pk=comment.author.id %}">{{ comment.author }}</a> {{ comment.created_on }}</p> <p class="spacer290">{{ comment.comment }}</p> <div class="spacer289"> <div class="upvote-comment-count">{{ comment.total_comment_upvotes }}</div> <div class="hide-delete"> <button type="button" class="button6" data-href="{% url 'Suggestions:suggestion_comment_like' comment.id %}">Like</button> </div> <div class="hide-delete"> <button type="button" class="button2" data-href="">Reply</button> </div> {% if comment.author == request.user %} <button type="button" class="button4" id="{{ comment.id }}" pk="{{ object.pk }}" href="{% url 'Suggestions:suggestion_comment_edit' object.pk comment.id %}">Edit</button> <div class="spacer159" … -
Accessing TemporaryFilePath in form_valid Django
Currently my users are able to upload files, as I am deployed via Heroku I am using Django-storages to upload to AWS S3 buckets. I am using a CreateView/UpdateView as below, this works well however I now want to be able to run an operation on the file before uploading to AWS, my research insofar suggests that I can use temporary_file_path() to do this in the form_valid however I am getting an error, UpdateView/CreateView class project_update(LoginRequiredMixin, UpdateView): model = Project form_class = ProjectForm template_name = "home/update_project.html" context_object_name = 'project' success_url = reverse_lazy("project-list") def form_valid(self, form): handle_uploaded_boq(form['boq_file'].temporary_file_path(), form.cleaned_data['project_title']) return super(project_update, self).form_valid(form) However I am getting the following error: 'BoundField' object has no attribute 'temporary_file_path' So what is the best way to run the operation handle_uploaded_boq() before the file is uploaded to AWS? -
Search bar in the models.CharField containing choiches Django
I wanted to know if there is a way to insert a search bar in the Django choices, that is instead of manually searching the various choices if it is possible to use a filter bar to search for our choice in Django Admin - Models. -
How to check if a variable is alphanumeric if acertain condition has been met
I am trying to check if the length of the user's username is 7. If the condition is satisfied, then I want to check if it is alphanumeric. If it isn't, I want to return the error below. You have entered an invalid username Here is My code if len(username) == 7: if username.isalnum() is False: self.errors[''] = self.error_class(["You have entered an invalid username"]) else: pass else: self.errors[''] = self.error_class(["You have entered an invalid username"]) -
Multiprocessing In Django Function with ZIP
Is it possible to use multi processing in Django on a request. #so if I send a request to http://127.0.0.1:8000/wallet_verify def wallet_verify(request): walelts = botactive.objects.all() #here I check if the user want to be included in the process or not so if they set it to True then i'll include them else ignore. for active in walelts: check_active = active.active if check_active == True: user_is_active = active.user #for the ones that want to be included I then go to get their key data. I need to get both api and secret so then I loop through to get the data from active users. database = Bybitapidatas.objects.filter(user=user_is_active) for apikey in database: apikey = apikey.apikey for apisecret in database: apisecret = apisecret.apisecret #since I am making a request to an exchange endpoint I can only include one API and secret at a time . So for 1 person at a time this is why I want to run in parallel. for a, b in zip(list(Bybitapidatas.objects.filter(user=user_is_active).values("apikey")), list(Bybitapidatas.objects.filter(user=user_is_active).values("apisecret"))): session =spot.HTTP(endpoint='https://api-testnet.bybit.com/', api_key=a['apikey'], api_secret=b['apisecret']) #here I check to see if they have balance to open trades if they have selected to be included. GET_USDT_BALANCE = session.get_wallet_balance()['result']['balances'] for i in GET_USDT_BALANCE: if 'USDT' in i.values(): GET_USDT_BALANCE = … -
Method get_context_data is called twice. Template tags in django
the database is accessed twice, once per in views, second time in templatetags. I tried to make a mixin, it still calls twice. how to remove the second call to the database? VIEWS class MoneyHomeView(CacheQuerysetMixin, RelatedMixin, ListView): model = Money paginate_by = 10 template_name = 'money/money_list.html' context_object_name = 'money' def get_context_data(self, *, object_list=None, **kwargs): context = super().get_context_data(**kwargs) if self._check_cached() == False: getQ = self._caching_queryset(self.getMoneyQuery()) else: getQ = self._get_cached_queryset() list_orders = getQ paginator = Paginator(list_orders, self.paginate_by) page = self.request.GET.get('page') return context def getMoneyQuery(self): return Money.objects.all() MIXIN class CacheQuerysetMixin: _cached_queryset: list = None def _caching_queryset(self, queryset): if not self._cached_queryset: self._cached_queryset = queryset return self._cached_queryset def _check_cached(self): if not self._cached_queryset: return False return True def _get_cached_queryset(self): if not self._cached_queryset: self._cached_queryset = queryset return self._cached_queryset templatetag @register.simple_tag(takes_context=True) def url_replace(context, **kwargs): query = context['request'].GET.copy() for kwarg in kwargs: try: query.pop(kwarg) except KeyError: pass query.update(kwargs) return mark_safe(query.urlencode()) How to solve this problem? i think i need to change templatetags -
How to customize an error message for django-rest-framework-simplejwt blacklist()
I am trying to create a logout serializer that blacklist's the refresh token. But I got this error message: AssertionError: ValidationError raised by `LogoutSerializer`, but error key `incorrect_token` does not exist in the `error_messages` dictionary. I have tried adding the default_error_message dictionary as shown but it doesn't work class LogoutSerializer(serializers.Serializer): """ Serializes for user logout data""" refresh_token = serializers.CharField() default_error_message = { 'incorrect_token': ('Token is expired or invalid') } def validate(self, attrs): self.token = attrs['refresh_token'] return attrs def save(self, **kwargs): try: RefreshToken(self.token).blacklist() except TokenError: self.fail('incorrect_token') What is the correct way of solving this? -
Print items from a list using index of a for loop in jinja code
{% for index in length %} {{index}} <img src={{image_url.index}} width="200" height="250"> {% endfor %} length contains number list from 0 to 38 i.e. [0,1,2,......38] The image_url contains the list of image urls that I want show in my webpage. The {{index}} code run properly and show the index number from 0 to 38. But when I try to display image using {{image_url.index}} no image is displayed. Is there an solution for this?