Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django list display of foreign key attribute that is boolean field using check or cross icons
My problem is similar to this thread: Can "list_display" in a Django ModelAdmin display attributes of ForeignKey fields?. I want to display a foreign key attribute from the list display. This attribute is a BooleanField. Normally, it would display a check or cross if the admin page is on the model itself containing the field. Such as this: However when I reference this to other admin page. class ProofOfPaymentAdmin(admin.ModelAdmin): list_display = ('id', 'reference_number', 'user', 'is_subscribed',) def is_subscribed(self, obj): return obj.user.is_subscribed The return from the list display is the boolean values True or False. How can I change this to display the icons check or cross similar from the above? -
How to return to main page (with POST data) after viewing detail pages in Django
I am building a Django (4.1) app that managers can use to view production data. An initial GET request /prod-query request displays a blank form with machine, part, and date fields. Submitting the form creates a POST request to /prod-query that displays a list of machines with production data filtered by the above data. Each row of the above data is a link to a detail page for that machine. The detail page for that machine has Next and Prev buttons that show the same detail page for previous or next time periods. I also have a Back button that I want to return to the last /prod-query with the POST data so it displays the last data set. Note: I can't use onclick="history.back() as the page I want may not be the last page viewed. Is there a simple way to do this I am missing? Do I need to put the POST data in the session and check for it when I make a GET to the original URL? The data size isn't an issue. Just thinking there should be a more Pythonic way. For now, I am going to create a form in the detail pages that … -
django-wkhtmltopdf not loading apex charts
I'm working on a project where I need to export some reports about a certain entity, using wkhtmltopdf with an html template that includes some charts from ApexCharts.js. The charts load fine in a rendered html but not in the pdf generated. Here's a sample of what I'm trying to do: in report.html <!DOCTYPE html> <html lang="en"> <head> <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/apexcharts"></script> </head> <body> <div id="chart"> </div> </body> <script> var options = { chart: { width: '100%', type: 'line', animations: { enabled: false, }, }, series: [{ name: 'sales', data: [30,40,35,50,49,60,70,91,125] }], xaxis: { categories: [1991,1992,1993,1994,1995,1996,1997, 1998,1999] } } var chart = new ApexCharts(document.querySelector("#chart"), options); chart.render(); </script> </html> in views.py from django.core.files import File from io import BytesIO from wkhtmltopdf.views import PDFTemplateResponse from django.views.generic import View from django.shortcuts import redirect from django.urls import reverse_lazy class GenerateReportView(View): filename = "myfile.pdf" template_name = "reports/report.html" def get(self, request): response = PDFTemplateResponse(request=self.request, template=self.template_name, filename=self.filename, context={}, show_content_in_browser= False, cmd_options = { 'quiet': None, 'enable-local-file-access': True, 'encoding': 'utf8', 'no-stop-slow-scripts': True, 'page-size': 'A4', 'javascript-delay': 5000, } ) file = File(BytesIO(response.rendered_content), name="myfile.pdf") Report.objects.create( file=file, ) return redirect(reverse_lazy("home:home")) I have tried the following, with no luck: Using imgkit to pre-convert the chart to an image. Disabled the … -
locate all DOM elements inside script contianer
In my Django web page i have a for loop which creates multiple instances of a form. In each form i would like to execute some Javascript code when the page is loaded. My problem is I am unsure how to reference the form that contains the script inside the Javascript code. I am trying to search through each input in each form {% for item in items %} <form class="entry-item-container" action="{% url 'view_POST' view %}" method="post"> {% csrf_token %} <script> var inputs = form.getElementsByTagName("input") var input_values = [] for (let i = 0; i<inputs.length; i++) { if (inputs[i].type != "hidden") { input_values.push(inputs[i].value) } } </script> ... <!-- inputs --> ... {% endfor %} i would like the form in var inputs = form.getElementsByTagName("input") to reference the parent form -
Passing variable from urls.py to html
I set django-built-in messages to pass some info from my views.py file to html file directly. I'm using directly messages.info(request, "User credentials are updated.") to send messages. As you see below, it works fine. Right now, I am planning to pass variables from urls.py to HTML directly. Something like below: path('password_change_done/', auth_views.PasswordChangeDoneView.as_view(template_name="account/dashboard.html"), **{'messages': 'User credentials are updated.'}**, name='password_change_done') When I search for it, I see that I can send a dictionary but it doesn't work for me. I tried to stick the same format(messages dictionary) where HTML expects. **{'messages': 'User credentials are updated.'}** Part of my urls.py file: # Password change # 1 ) Submit password change form path('password_change/', auth_views.PasswordChangeView.as_view(template_name="account/password/password-change-form.html"), name='password_change'), # 2 ) Success message stating that password is changed path('password_change_done/', auth_views.PasswordChangeDoneView.as_view(template_name="account/dashboard.html"), **{'message': 'User credentials are updated.'}**, name='password_change_done'), Part of my dashboard.html file: <!-- Django's built-in message template part --> {% for message in messages %} {% if message.level == DEFAULT_MESSAGE_LEVELS.SUCCESS %} <h6 id="message-timer" class="alert alert-success text-center"> <i class="fa fa-sign-out" aria-hidden="true"></i> &nbsp; {{ message }} </h6> {% endif %} {% if message.level == DEFAULT_MESSAGE_LEVELS.ERROR %} <h6 id="message-timer" class="alert alert-danger text-center"> <i class="fa fa-exclamation" aria-hidden="true"></i> &nbsp; {{ message }} </h6> {% endif %} {% if message.level == DEFAULT_MESSAGE_LEVELS.INFO %} <h6 … -
Django rest freamework: get a path parameter in the serializer
I request to a service with this path: /api/story_step/<chatbot>/<story_name>/ And in the suitable Django serializer I have the following field: interaction_name = serializers.CharField(source='interaction.name', read_only=True) Which is a reference to another table field: interaction = models.ForeignKey('interactions.Interaction', models.CASCADE, 'story_interaction', 'story_interaction') Is there any way to filter that field by the path parameter in order to see only the interactions of that defined chatbot? Thanks. -
How to hash previously saved password in phpmyadmin in Django
I'm building a Django app and working with existing database with it's own data. I built login function and creating user accounts from admin side. My question is how can I hash previously saved passwords in the database instead of re-creating accounts. Note: saved passwords are plain text not hashed. My views.py: creating accounts: @admin_login_required def add_emp(request): if request.method == 'POST': user_name = request.POST['user_name'] user_email = request.POST['user_email'] user_otj = request.POST['user_otj'] user_password = pwo.generate() user_password1 = make_password(user_password) empObj = User.objects.create(user_name=user_name, user_email=user_email, user_password=user_password1, user_otj=user_otj) if empObj: subject = 'Advanced Analytics Portal - Login Info' message = f'Name : {user_name}, \n Email : {user_email}, \n Password : {user_password} \n FROM - AA Portal' email_from = settings.EMAIL_HOST_USER send_mail(subject, message, email_from, [user_email]) messages.success(request, "Employee was added successfully!") return HttpResponseRedirect('/create-emp') else: messages.error(request, "Some error was occurred!") return HttpResponseRedirect('/create-emp') return render(request, 'AddEmp.html') login view: def user_login(request): if request.method == "POST": user_email = request.POST['user_email'] user_password = request.POST['user_password'] user_details = User.objects.filter(user_email=user_email).first() if user_details and check_password(user_password, user_details.user_password): request.session['logged_in'] = True request.session['user_email'] = user_details.user_email request.session['u_id'] = user_details.user_email request.session['user_name'] = user_details.user_name request.session['u_type'] = "emp" return HttpResponseRedirect('/user_index') else: return render(request, 'EmpLogin.html', {'msg': "0"}) else: return render(request, 'EmpLogin.html') -
Django: how to clear session variables on page load, that way that paginator won't clear them
I'm storing filter data in session variables. How to clear them only when user in reloading or navigating to that page, but keep them when user is using pagination? def boxes(request): user = request.user log_in_form = CustomUserLogInForm() filter_form = FilterForm() # THAT MAKES SESSION VARIABLES USABLE ONLY ONCE, THAT IS GREAT UNLESS USER IS USING PAGINATION if filter := request.session.get("box_filter"): boxes = Box.objects.all().filter(id__in=filter) form_city = request.session.get("form_city") form_radius = request.session.get("form_radius") del request.session["box_filter"] del request.session["form_city"] del request.session["form_radius"] else: boxes = Box.objects.all() form_city = "" form_radius = "" paginator = Paginator(boxes, 5) page = request.GET.get("page") boxes = paginator.get_page(page) if boxes.paginator.num_pages < 5: page_numbers = range(1, boxes.paginator.num_pages + 1) else: if boxes.number < 3: min = 1 else: min = boxes.number - 2 if boxes.number > boxes.paginator.num_pages - 2: max = boxes.paginator.num_pages + 1 else: max = boxes.number + 3 page_numbers = list(range(min, max)) page_numbers.append("...") page_numbers.append(boxes.paginator.num_pages) log_in(request) if request.method == "POST": form = FilterForm(request.POST) if form.is_valid(): cities = pd.read_csv(settings.BASE_DIR / "static/cities_db.csv", sep=";") city = form.cleaned_data["city"] radius = form.cleaned_data["radius"] request.session["form_city"] = city request.session["form_radius"] = radius city_row = cities.loc[cities["Name"] == city.title()] city_lat, city_lon = str(city_row["Coordinates"].iloc[0]).split(", ") tmp_box_filter = [] for box in Box.objects.all(): if geopy.distance.geodesic((float(city_lat), float(city_lon)), (float(box.lat), float(box.lon))).m <= float(radius): tmp_box_filter.append(box.id) request.session["box_filter"] = tmp_box_filter return redirect("boxes") … -
Form marked for deletion but empty FormSet.deleted_forms
I've got a piece of code similar to the following: from django.forms import inlineformset_factory class EmailForm(forms.ModelForm): class Meta: model = MyModel EmailFormSet = inlineformset_factory( MyRelatedModel, MyModel, form=EmailForm, can_delete=True, extra=0 ) And I've got a custom class-based view which works perfectly fine for creating/saving new MyModel instances and for editing existing instances. When I mark a form / an instance for deletion, I can see my view receives the following POST method: <QueryDict: { 'csrfmiddlewaretoken': ['XXX'], 'email-TOTAL_FORMS': ['1'], 'email-INITIAL_FORMS': ['1'], 'email-MIN_NUM_FORMS': ['0'], 'email-MAX_NUM_FORMS': ['1000'], 'email-0-id': ['94ef2d4c-b2fc-4082-a460-e4344ddb20d4'], 'email-0-value': ['12345'], 'email-0-DELETE': ['on'], }> I believe this is, again, the expected behavior, in particular the formset.data do contain {'email-0-DELETE': ['on']} and the form is valid. However, the corresponding instance is not deleted. Indeed, when I display formset.deleted_forms, it turns out to be an empty list. Why? I've tried to deep dive into Django's inner mechanisms and I've noticed the method deleted_forms relies on another called _should_delete_form which simply returns form.cleaned_data.get(DELETION_FIELD_NAME, False). But in my case, form.cleaned_data only contains {'value': '12345'}, no "DELETE" key... So how is _should_delete_form supposed to return something else than False? Am I supposed to explicitly add a DELETE field to EmailForm, isn't the formset supposed to manage that extra field? -
is postman setting different for mac and windows? facing issue for postman in mac but same is working fine in windows
is postman setting different for mac and windows? facing issue for postman in mac but same is working fine in windows is postman setting different for mac and windows? facing issue for postman in mac but same is working fine in windows -
Optimizing Django db queries for Viewset
I recently was tasked to optimize db queries and performance of some of our django rest apis written in drf and was able to successfully use prefetch_related() to implement them. But there is one usecase I have been unable to resolve and looking for support on the same. Here goes the structure: Models.py class Section(models.Model): section_tags = models.ManyToManyField(AssetTag) section_name = models.CharField(max_length=200) section_createdate = models.DateTimeField(auto_now=True) class Collection(models.Model): section = models.ForeignKey(Section, on_delete=models.CASCADE, related_name="collection_set") system_tags = models.ManyToManyField(AssetTag, blank=False, related_name='system_tags_poster_collections') card = models.ManyToManyField(Card) class Card(models.Model): tag = models.ManyToManyField(CardTag) # should we deprecate? system_tags = models.ManyToManyField(AssetTag, blank=False, related_name='system_tags_poster_cards') card_name = models.CharField(max_length=200) views.py class SectionViewset(viewsets.ModelViewSet): serializer_class = serializers.SectionSerializer http_method_names = ['get'] def get_queryset(self): queryset = Section.objects.filter(section_status=True, section_expiredate__gte=datetime.now()) return queryset serializer.py class SectionSerializer(serializers.ModelSerializer): collection_set = CollectionSerializer(many=True, read_only=True) class FilteredCollectionSerializer(serializers.ListSerializer): def to_representation(self, data): data = data.filter(collection_status=True, collection_expiredate__gte=datetime.now()) return super(FilteredCollectionSerializer, self).to_representation(data) class CollectionSerializer(serializers.ModelSerializer): card = CardSerializer(many=True, read_only=True) system_tags = AssetTagBadgeSerializer(many=True, read_only=True) class Meta: list_serializer_class = FilteredCollectionSerializer model = Collection fields = ('id', 'card', 'system_tags') I am unable to apply prefetch_related() to get any optimization of the queries on the SectionViewSet since it is sort of a reverse relationship in the Collection Model. Is there any way to optimize calls to db since I see many calls for card__tag and … -
Set height of div based on previous div
I have a for loop that creates product cards using Bootstrap. I want to add an additional card after where the user can click through to view all products in that category. I want that additional card to always been the same size and it's previous card. I have tried several JavaScript solutions from Google but can't get it to work. My code is as follows: {% extends "base.html" %} {% load static %} {% block content %} <!-- Disposable Vape Section --> <section> <div class="overlay"></div> <div class="container-fluid"> <div class="row"> <div class="col text-center mt-5"> <h2 class="logo-font">Shop Disposables - Over 100 flavours available</h2> <hr class="w-50 mb-5"> </div> </div> <div class="row"> <div class="product-container col-10 offset-1"> <div class="row mt-1"> {% for product in products %} {% if product.category.name == 'disposable_vape' %} <div class="col-sm-6 col-md-6 col-lg-4 col-xl-3"> <div class="card h-100 border-0"> {% if product.image %} <a href="{% url 'product_detail' product.id %}"> <img class="card-img-top img-fluid" src="{{ product.image.url }}" alt="{{ product.name }}"> </a> {% else %} <a href="{% url 'product_detail' product.id %}"> <img class="card-img-top img-fluid" src="{{ MEDIA_URL }}noimage.png" alt="{{ product.name }}"> </a> {% endif %} <div class="card-body pb-0"> <p class="mb-0">{{ product.name }}</p> </div> <div class="card-footer bg-white pt-0 border-0 text-left"> <div class="row"> <div class="col"> <p class="lead mb-0 … -
Inserndo valores nulos no postgres atraves do django
Escrevi um código que recebe imagens do formulário html e as converte em valores binários e insere no postgres, desta forma tudo fica funcional mas quando não insiro nada no formulário html e clico no botão enviar dá um erro, isso quer dizer que não devo enviar campos de arquivo null para o django. gostaria de saber se existe alguma forma de inserir valores nulos no postgres através do django mas recebendo do formulário html o codigo python : def document(request): if request.method=='POST': uuid = request.POST['uuid'], facilitador = request.POST['facilitador'], enumerador = request.POST['enumerador'], certificado_ref = request.POST['certificado_ref'], provincia = request.POST['provincia'], distrito = request.POST['distrito'], comunidade = request.POST['comunidade'], provedor = request.POST['provedor'], observacao = request.POST['observacao'], data_submissao = request.POST['data_submissao'], data_certificado = request.POST['data_certificado'], img_mapa = request.FILES["img_mapa"].read() img_certificado = request.FILES["img_certificado"].read() formulario1 = request.FILES["img_formulario1"].read() formulario2 = request.FILES["img_formulario2"].read() formulario3 = request.FILES["img_formulario3"].read() formulario4 = request.FILES["img_formulario4"].read() formulario5 = request.FILES["img_formulario5"].read() img_historia = request.FILES["img_historia"].read() map_mulheres = request.FILES["map_mulheres"].read() map_homens = request.FILES["map_homens"].read() map_jovens = request.FILES["map_jovens"].read() map_idosos = request.FILES["map_idosos"].read() cartograma = request.FILES["map_cartograma"].read() img_estatutos = request.FILES["img_estatutos"].read() img_coordenadas = request.FILES["map_coordenadas"].read() try: try: insert_script="INSERT INTO public.delimited_community_geoportal_source (uri,facilitator,enumerator,certificate_ref,province_id,district_id,community_name,financer,obs,submission_date,certificate_date,img_sketch_map,img_certificate,img_form_1,img_form_2,img_form_3,img_form_4,img_form_5,img_history,img_maps_men,img_maps_women,img_maps_youth,img_maps_old,img_cartograma,img_statutes_assoc,img_coords) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)" insert_values = (uuid,facilitador,enumerador,certificado_ref,provincia,distrito,comunidade,provedor,observacao,data_submissao,data_certificado, psycopg2.Binary(img_mapa),psycopg2.Binary(img_certificado),psycopg2.Binary(formulario1),psycopg2.Binary(formulario2),psycopg2.Binary(formulario3),psycopg2.Binary(formulario4),psycopg2.Binary(formulario5), psycopg2.Binary(img_historia),psycopg2.Binary(map_mulheres),psycopg2.Binary(map_homens),psycopg2.Binary(map_jovens),psycopg2.Binary(map_idosos), psycopg2.Binary(cartograma),psycopg2.Binary(img_estatutos),psycopg2.Binary(img_coordenadas),) cur.execute(insert_script,insert_values) conn.commit() messages.success(request, "Ficheiro carregado com sucesso") except(Exception, psycopg2.Error) as error: messages.success(request, "Erro no carregamento do ficheiro",error) finally: pass context = { } return render(request,'document.html', … -
django sub admin panel
I am working on the Django admin panel but now client is asking me that he need a functionality to create sub admin from the admin panel and provide some permission to sub admin flow - Here admin need a tab like sub admin management- admin will be able to create new admin by providing email, name photo, once admin submit the details of the sub admin link will be shared to the sub admin inputted email from where he can set his password, admin will also have the functionality to provide different permission to different sub admin, will be able to change these permission in future i have 6 application in admin where admin is admin to perform cur operation on user management, device management. i.e permission for sub admin will be for example sub admin can view user management but view and edit device management and so on. Questions How we can register the sub admin? i.e to register the super admin we go to terminal and write the commands to register the sub admin now registration for sub admin is done from admin panel How we can provide different permission to the sub admin Do I need … -
Efficient debugging Django with pdb – like Sentry
I use pdb to debug in Django. Sometimes it works, sometimes it does not catch the issue, just runs over the error. I have another example, the way how Sentry shows the bugs. Exactly at the place where it is relevant. Could I use pdb similarly? Maybe via the "where" command? It would be so useful! An example: if there is a bug in one of the serializers, it is so hard to find the relevant code place. Django server just gives a "non_field_errors":["Something unexpected has occured. Please contact an admin to fix this issue."]. On the other hand, Sentry can show the hot spot. So it "can" be found. I would like to find it with pdb also! -
How to fetch text value dynamically when clicked on it using javascript
I have a DJANGO app and want to get the values of text in JAVASCRIPT when it gets selected but getting undefined instead. my code: <div class="askedDiv"> {% for i in recentlyUsed %} <p onclick="myFunction()" id="myBtn">{{i}}</p> {% endfor %} </div> in js: function myFunction() { const x = document.getElementById("myBtn").value; console.log(x) } but in console i'm getting undefined. How can i get different text name , when it is selected from recentlyUsed list. As I'm new to this anyhelp will be thankfull. -
How to change state (FSM) of Aiogram bot outside of message handlers?
I have Aiogram bot workings inside Django REST server. If there is POST request coming in Django I need to change the state of Aiogram bot, but I don't know how to do it outside of message handlers and how do I clarify the change of state of specific bot. Mby there is some other ways to solve this? -
How to get data of first column from table in django template
How to get data of first column from table in django template views.py def get_table(request): table = Table.objects.all() return render(request, 'template.html', {'table': table}) template.html {% block 'content' %} <h1 class="title">{{table|first.title}}</h1> {% endblock %} But I'm getting TemplateSyntaxError: Could not parse the remainder: '.title' from 'table|first.title' Database (db.sqlite3): id title 1 Testing title 2 A really good title I have tried to put {% for data in table %} <h1 class="title">{{data.title}}</h1> but that is not the case. -
How to update foreign key from another model Django
I'm fairly new to Django, I have two models usecase and usecase_type. usecase table has a fk of usecase_type. I'm trying to update usecase details including the usecase_type value. How can I update the value plus show the usecase_type in a dropdown list to update. My views.py: def edit_usecase(request, ucid): try: usecase_details = Usecase.objects.filter(usecase_id=ucid) context = {"usecase_details":usecase_details[0]} if request.method == "POST": usecase_name = request.POST['usecase_name'] usecase_description = request.POST['usecase_description'] usecase_type = request.POST['usecase_type'] usecase_details = Usecase.objects.get(usecase_id=ucid) usecase_details.usecase_name = usecase_name usecase_details.usecase_description = usecase_description usecase_details.usecase_type_id = usecase_type usecase_details.save() if usecase_details: messages.success(request, "Usecase Data was updated successfully!") return HttpResponseRedirect(reverse('update-usecase', args=[ucid])) else: messages.error(request, "Some Error was occurred!") return HttpResponseRedirect(reverse('update-usecase', args=[ucid])) return render(request, 'UpdateUsecase.html', context) except: messages.error(request, "Some Error was occurred!") return HttpResponseRedirect(reverse('update-usecase', args=[ucid])) my template: {% block body %} <div class="row d-flex"> <div class="col-12 mb-4"> <div class="card border-light shadow-sm components-section d-flex "> <div class="card-body d-flex "> <div class="row mb-4"> <div class="card-body"> <div class="row col-12"> <div class="mb-4"> <h3 class="h3">Edit usecase details:</h3> </div> <!-- <li role="separator" class="dropdown-divider border-black mb-3 ml-3"></li> --> <form action="/update-usecase/{{usecase_details.usecase_id}}" method="POST"> {% csrf_token %} <div class="form-row mb-4"> <div class="col-lg-8 mr-f"> <label class="h6" for="exampleFormControlTextarea1">Usecase name:</label> <input value="{{usecase_details.usecase_name}}" type="text" name="usecase_name" class="form-control" placeholder="" required> </div> <div class="col-lg-8 mr-f"> <label class="h6" for="exampleFormControlTextarea1">Usecase description:</label> <input value="{{usecase_details.usecase_description}}" type="text" name="usecase_description" class="form-control" placeholder="" required> … -
How does OCPP work with the Django rest framework?
I need to create a project with ocpp and Django rest framework I start to create project with ocpp but was not able to connect with the rest framework -
How can i start in cutting stock problem?
I am looking to build a web app (Using React + Django) for 1D and 2D cutting stock problem. After searching for a while i am a bit lost on what can i start with and what algorithms to implement and how. Any help and resources that are recommended to start with would be appreciated. Thank you -
NGINX max upload has no effect
I'm using nginx proxy docker for my django project but I'm getting 413 Request Entity Too Large when uploading images more than about 3MB. I put client_max_body_size 1024M; in htttp, server and location in nginx.conf and default.conf but it doesn't work at all. Should I rewrite any other configs or uwsgi? -
Serializer a input data with list [Django restframework]
I have a question with to declare an input data { “id”: 1235, “products”:[ { “product_id”: 1, “descriptions”: “b” }, { “product_id”: 2, “descriptions”: “a” }, { “product_id”: 3, “descriptions”: “c” } ] } So I have make the serializer like this id = serializers.CharField(write_only=True, required=true) product_id= serializers.Integer()(required=False) descriptions = serializers.CharField(max_lenght=300)<br> products = [serializer.JSONField()] Is it correct for it ? Thank you everyone How get the django serializer for the list of a data -
Django Template tag 'with' not working as expected
I'm trying to use Django Template 'with' tag to alternate between two icons, the solid icon represents liked posts (called chirps in this project), and the regular icon represent non-liked posts(chirps). After some iterations this is the code I'm trying to implement but for some reason the last conditional 'if' always interpret the variable 'blahblah' as False, even when has been reassigned to True: <span style="float: right"> {% with blahblah=False %} {% for like in likes %} {% if like.userId == currentUserId and chirp == like.chirpId %} {% with blahblah=True %} <i id="like{{ chirp.id }}" class="fa-solid fa-heart likeBttn"></i> {% endwith %} {% endif %} {% endfor %} {% if not blahblah %} <i id="like{{ chirp.id }}" class="fa-regular fa-heart likeBttn"></i> {% endif %} &nbsp; <span class="count{{chirp.id}}">{{liked}}{{ chirp.numLikes }}</span> likes {% endwith %} </span> I have tried to use {% empty %} tag but doesn't really apply this problem because 'likes' is never empty. This is the simplest implementation to the problem but unfortunately is not working. -
Django - When using Easy Thumbnails how to force a field to convert the thumbails to JPG even if PNG with alpha was provided
When using Easy Thumbnails you can globally configure that all images (even PNGs with alpha) are converted to JPG by adding this to your settings.py THUMBNAIL_TRANSPARENCY_EXTENSION = 'jpg' But the problem is that I don't want to force ALL of my images in my application to be converted to JPG because I have some models that require images with alpha (png). I have a model for a blog article where I need the image to ALWAYS be converted to JPG. No matter if people upload PNGs with alpha. class Article(BaseModel): title = models.CharField(max_length=255, unique=True) image = ThumbnailerImageField(upload_to='blog/articles/image') Right now many people are uploading PNG's with alpha enabled (although the image doesn't have any transparency) and this is preventing the Thumbnailer to compress them as JPG making many of the thumbnails 500kb(png) instead of like 70kb(jpg). How can I specify to always convert these article images to JPG?