Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
In djangocms-picture how to set a default maximum image size?
I would like to set a default maximum size of images in the djangocms-picture plugin. I would like to do this at template level. This simple template for example: {% load thumbnail %} <img src="{% thumbnail instance.img_src 'golden_ratio_xlarge' %}"> Gives this error: SuspiciousFileOperation at /en/ The joined path (/media/filer_public_thumbnails/filer_public/a3/07/a3073ea1-a798-43c0-869f-689de5f53e7e/sawa.png__420x233_q85_subsampling-2.png) is located outside of the base path component (/home/mogoh/src/git.noc.ruhr-uni-bochum.de/ceres/website/ceres/media) -
Using Python/Django how do I substitute values from an external source into an HTML page
I am relatively new to Django and am trying to substitute values from an external source into an HTML page? Using the following HTML snippet: <div>UID: -3SDfguwvNuurPe44AnUjGdzOj_guWVP3QPjmhZyWsA1</div> <div>Validic ID: 5e220365bdb13500b03075a2</div> <div>Created: 2020-01-17T18:56:37Z</div> <div>Updated: 2020-01-17T18:56:37Z</div> I want to replace the text value for each of those rows (to the right of the "key:" with the value retrieved from a JSON response for each of the "keys". I have tried: <div>UID: {{ display_uid }}</div> <div>Validic ID: {{ display_vid }}</div> <div>Created: {{ display_created }}</div> <div>Updated: {{ diplay_updated }}</div>``` The examples I have found have shown how to build forms and use text fields/text areas, but nothing for a plain HTML page. Anybody got suggestions? Thanks. Jeff Brown -
How to replace comment column in django-simple-history view with action column from standard django admin view?
I'm trying to enhance tracking options of instances in my database. I've applied django-simple-history app. It helps a lot except of the column COMMENTS which I find totally useless. Comments column in django-simple-history view I would prefer to replace the column comments withe column ACTION from the standard history admin view. Action column in standard admin view Is there an easy way to do that? -
Replicating Django forms request.FILES to upload multiple image files using smartfields
I'm trying to take a single image using Django forms and upload it with resized version under 3 headers. I'm even able to do so with request.POST QueryDict but not with request.FILES MultiValueDict even after it shows filled data for respective field names. My Views.py def image_add(request,article_id): template_name = 'blogs/image_add.html' articles = Article.objects.get(article_id=article_id) form = ImageAddForm if request.method == 'POST': image = request.FILES["image_1080"] request.FILES['image_800'] = image request.FILES['image_350'] = image print(request.POST) print(request.FILES) form = ImageAddForm(request.POST, request.FILES) if form.is_valid(): new_form = form.save(commit=False) new_form.dir_id = article_id new_form.save() return redirect('/') context = {'form':form,'articles':articles} return render(request, template_name,context) My Models.py from smartfields import fields from smartfields.dependencies import FileDependency from smartfields.processors import ImageProcessor class Images(models.Model): dir_id = models.CharField(max_length=10,null=True) image_1080 = fields.ImageField(upload_to=img_1080_dir_path, name="image_1080", dependencies=[ FileDependency(processor=ImageProcessor( format='PNG', scale={'max_width': 1080, 'max_height': 1080})) ]) image_800 = fields.ImageField(upload_to=img_800_dir_path, blank=True, name="image_800", dependencies=[ FileDependency(processor=ImageProcessor( format='PNG', scale={'max_width': 800, 'max_height': 800})) ]) image_350 = fields.ImageField(upload_to=img_350_dir_path, blank=True, name="image_350", dependencies=[ FileDependency(processor=ImageProcessor( format='PNG', scale={'max_width': 350, 'max_height': 350})) ]) My Forms.py class ImageAddForm(forms.ModelForm): class Meta: model = Images fields = ('name','alt_text','image_1080') widgets = { 'name': forms.TextInput(attrs={'class': 'form-control'}), 'alt_text': forms.TextInput(attrs={'class': 'form-control'}), 'image_1080': forms.ClearableFileInput(attrs={'class': 'form-file-input'}) } This saves only one image - 'image_1080' but not the other two. -
Querying model by ForeignKey to receive data in another ForeignKey?
I am having trouble running a query through a table that I built as basically a linkage type table to link Company and Package class CompanyPackageLink(models.Model): company = models.ForeignKey('business.Company', related_name='company_packages') package = models.ForeignKey('business.Package', related_name='packages') I am trying to query the CompanyPackage table by company and then retrieve all packages associates to that query. I have something like... company = Company.objects.get(employee=self.request.user) company_packages = CompanyPackageLink.objects.filter(company=company).select_related('package') Now this returns a correct quesyset, but it returns the CompanyPackage instance. <QuerySet [<CompanyPackageLink: companyA: PackageA>, <CompanyPackageLink: CompanyB: PackageB>]> I would like my query to return the actual Package model instance where I can retrieve name, price, etc. So I would like the returned queryset to actually return this.. <QuerySet [<Package: $100.00>, <Package: $200.00>]> Any help is appreciated! -
Adding a language field to the login template in Django
I have to start a project in Django, which should be able to translate in three languages (Spanish, English and Italian). I have the 3 languages defined within the settings.py file, as it looks: LANGUAGES = [ ('es', _('Español')), ('en', _('English')), ('it', _('Italiano')), ] My intention (I am not sure if it is the one indicated) is that when the user logs in, they enter their username, their password and the language with which they will work and from there the application establishes the menus, forms, etc. according to to the indicated language. My first approach was to extend the user model by incorporating a language field, as seen: class User(AbstractUser): language = models.CharField(max_length=10, choices=settings.LANGUAGES, default=settings.LANGUAGE_CODE) modifying the AUTH_USER_MODEL variable: AUTH_USER_MODEL = 'usuarios.User' and modify the login form, as it looks: class LoginForm(ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) #self.fields['username'].widget.attrs['autofocus'] = True class Meta: model = User fields = 'username', 'password', 'language' widgets = { 'username': forms.TextInput( attrs={ 'placeholder': 'Ingrese su username', } ), 'password': forms.PasswordInput(render_value=True, attrs={ 'placeholder': 'Ingrese su password', } ), 'language': forms.SelectMultiple(attrs={ 'class': 'form-control select2', 'style': 'width: 100%', 'multiple': 'multiple' }) } As well as, add one more field to the login template: <div class="form-group form-primary"> {{form.username|add_class:'formcontrol'|attr:'type:text'}} … -
How to re-display formset & Select2 field with selected value on form error in Django
After searching for several days and trying different options, I decided to finally post the issue and question. I have a template that has a form and 2 different formsets. One of the formsets uses an intermediate model with a GenericForeignKey that will reference two other models. For the formset, I am using an inlineformset and adding a CharField which is used with Select2 to make an ajax call to check the two other models. The value returned by the ajax call will be a json/dict with 3 key/value pairs. The issue I am having is that when the template is submitted and there are errors, how can I redisplay the value that was entered in the Select2 CharField when the template is presented again? The value is in self.data and is sent back to the template. However, everything I've tried so far will not redisplay the select2 field with the value selected previously or the values that were submitted. The submitted values are returned to the template in a json/dict, key/value, format under form.fieldname.value but I am not sure how I can use that to repopulate the select2 field. I appreciate any suggestions or links. If there is an … -
Django: return distinct set of many to many relationship belonging to a particular model
I want a query that returns all the distinct tags belonging to all the entries in Model A. I suspect it's possible with clever query and a bit of filtering, but I can't work it out. I want to minimise database hits. Models: class Tag(models.Model): name = models.CharField(max_length = 50,) category = models.CharField(max_length = 50, blank=True) class A(models.Model): ... tags = models.ManyToManyField(Tag, blank=True) class B(models.Model): ... tags = models.ManyToManyField(Tag, blank=True) My solution in the meantime is: tags = list() for a in A.objects.all(): for t in a.tags.all(): if t not in tags: tags.append(t) Is there an elegant solution to achieve the above functionality? -
Django subsequent StringAgg with grouping
I'm using Django with postgresql. I have 3 tables with m2m relations: movies, genres and persons. Each person can have it's own role as actor, writer, or director. ---------|----------|------|--------------| Dark Star|Sci-Fi |Actor |Brian Narelle | Dark Star|Sci-Fi |Writer|John Carpenter| Dark Star|Sci-Fi |Writer|Dan O'Bannon | Dark Star|Sci-Fi |Actor |Cal Kuniholm | Dark Star|Comedy |Actor |Brian Narelle | Dark Star|Comedy |Writer|Dan O'Bannon | Dark Star|Comedy |Actor |Cal Kuniholm |``` What i'm trying to reach is grouped by genres and persons name and concatenated name fields for each movie: ---------|--------------|------|---------------------------------------| Dark Star|Comedy, Sci-Fi|Actor |Brian Narelle, Cal Kuniholm, Dre Pahich| Dark Star|Comedy, Sci-Fi|Writer|Dan O'Bannon, John Carpenter |``` Using raw sql it's quite easy to reach just subsequently group and string_agg subqueries. from ( select t.title, string_agg(t.genre_name, ', ' ORDER BY t.genre_name) as genres, t.role, t.name from ( SELECT "movies_filmwork"."title", "movies_genre"."name" as "genre_name", "movies_person"."role", "movies_person"."name" FROM "movies_filmwork" LEFT OUTER JOIN "movies_filmwork_genres" ON ("movies_filmwork"."id" = "movies_filmwork_genres"."filmwork_id") LEFT OUTER JOIN "movies_genre" ON ("movies_filmwork_genres"."genre_id" = "movies_genre"."id") LEFT OUTER JOIN "movies_filmwork_persons" ON ("movies_filmwork"."id" = "movies_filmwork_persons"."filmwork_id") LEFT OUTER JOIN "movies_person" ON ("movies_filmwork_persons"."person_id" = "movies_person"."id") where "movies_filmwork"."title" = 'Dark Star' ) t group by t.title, t.role, t.name ) tt group by tt.title, tt.role, tt.genres order by tt.title, genres ;``` But i … -
create an appointment app with registered user and tomporary user in Django
I want to create an appointment app with Django with the following condition: doctors and reception can add appointments for registered patients patient who already register can add appointment only for them self doctors and reception can add appointments for non register patient(Temporary patient, for example) in the first and the 2nd condition, no need for adding information about the patient (because he adds them) in the 3rd doctor and reception have the ability to add information so my idea is whene the paitent is not register. create a tomprary user and the form (in template ) will add the option of adding more information this is my models.py file class User(AbstractUser): STATUS_CHOICES = (('paitent', 'paitent'), ('Doctor', 'Doctor'), ('reception', 'reception'), ('temporary', 'temporary')) STATUS_CHOICES_2 = (('yes', 'yes'), ('no', 'no')) type_of_user = models.CharField(max_length=200, choices=STATUS_CHOICES, default='paitent') allowd_to_take_appointement = models.CharField(max_length=20, choices=STATUS_CHOICES_2, default='yes') def is_doctor(self): if self.type_of_user == 'Doctor': return True else: return False def is_paitent(self): if self.type_of_user == 'paitent': return True else: return False def is_reception(self): if self.type_of_user == 'reception': return True else: return False def is_temporary(self): if self.type_of_user == 'temporary': return True else: return False def can_add_appointement(self): if self.allowd_to_take_appointement == 'yes': return True else: return False class Profile(models.Model): BLOOD_GROUPS = [ ('O-', 'O-'), … -
Anonymous user during google social authentication
I am using Django3.1.7 and Python3.9.0 to set up Google Social Login. Here is a snippet of my home view. class Home(APIView): def get(self, request, *args, **kwargs): authenticated = request.user.is_authenticated print("Authenticated: ", authenticated) print("User: ", request.user) return Response({"message": "Home"}, status=status.HTTP_200_OK) Here is a snippet of my AuthURL view. class AuthURL(APIView): @method_decorator(csrf_protect) @method_decorator(never_cache) def dispatch(self, request, *args, **kwargs): return super().dispatch(request, *args, **kwargs) def get(self, request, *args, **kwargs): SCOPE = "profile+email" uri = ( "https://accounts.google.com/o/oauth2/v2/auth?response_type=code" "&client_id={}&redirect_uri={}&scope={}" ).format(CLIENT_ID, REDIRECT_URI, SCOPE) return Response({"uri": uri}, status=status.HTTP_200_OK) Here is a snippet of my Login view. class LoginView(APIView): @method_decorator(csrf_protect) @method_decorator(never_cache) def dispatch(self, request, *args, **kwargs): return super().dispatch(request, *args, **kwargs) def get(self, request, *args, **kwargs): code = request.GET["code"] data = { "code": code, "client_id": CLIENT_ID, "client_secret": CLIENT_SECRET, "redirect_uri": REDIRECT_URI, "grant_type": "authorization_code", } token = post("https://oauth2.googleapis.com/token", data=data) response = post("https://oauth2.googleapis.com/tokeninfo", data=token) data = response.json() user = User.objects.filter(email=data["email"]).first() if user is None: user = User.objects.create_user(email=data["email"], username=data["name"]) login(request, user) print("Request User: ", request.user) return redirect("http://localhost:3000/") App.js const logIn = () => { fetch("http://localhost:8000/accounts/get-auth-url/") .then((response) => response.json()) .then((data) => { window.location.replace(data.uri); }); } const home = () => { fetch("http://localhost:8000/accounts/home/") .then((response) => response.json()) .then((data) => { console.log(data); }); } return ( <div className="App"> <button type="button" onClick={logIn}>Log In</button> <button type="button" onClick={home}>Home</button> </div> ); … -
Django Rest Framework allauth Authentication credentials were not provided
I am using django allauth for authentication this is my settings.py REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.TokenAuthentication', 'rest_framework.authentication.SessionAuthentication', ], 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated' ], } the installed app are these: 'rest_framework', 'rest_framework.authtoken', 'rest_auth', 'rest_auth.registration', 'allauth', 'allauth.account', and i am trying like way: curl -X POST "http://127.0.0.1:8000/api/v1/cinema-hall/" -H 'Authorizaion: Token 44eba1cdb1ecde6d3a55d6c85d7c4f44315f2c44' this error i am getting: {"detail":"Authentication credentials were not provided."} I see many similar post exist like this: Django Rest Framework Authentication credentials were not provided but those are not solved my issue. Can anyone tell me what is the possible reason of facing this error? -
Django collectstatic --no input Yes instead of no
I am using Django3 and i have currently the following command in my makefile for "Build" python3 manage.py collectstatic to automate my buildprocess with a pipeline i would like to get rid of the prompt that asks You have requested to collect static files at the destination location as specified in your settings: URL This will overwrite existing files! Are you sure you want to do this? Type 'yes' to continue, or 'no' to cancel i found that out that i can add "--no-input" for the collectstatic at the end, but this will answer "no" in this case. Is there a way how i could say the script to answer "Yes" by default instead? -
Django - AttributeError: type object 'HttpRequest' has no attribute 'GET'
I am trying to get input from a checkbox from a website to go through django. I have already been through stackoverflow and found someone doing the same thing but for some reason it doesn't work for me and I get an error telling me that there is no 'GET' attribute for HttpRequest even though it says there is on the django documentation. html: '' python: from django.http import HttpRequest hedgecutb = HttpRequest.GET.get("hedgecutb") error: hedgecutb = HttpRequest.GET.get("hedgecutb") AttributeError: type object 'HttpRequest' has no attribute 'GET' -
object get with mixin or def in models
is it possible to issue a get result, only with certain fields in models, and not all? where fields must be defined inside models, like def or mixin. something like clean_data if a method is requested view cls = Class.objects.get(related_uuid='xxx') you only need to display device and related_uuid, but define this in models.py itself, not in views.py models class Orders(models.Model): device = models.CharField(max_length=150) serial = models.CharField(max_length=150, blank=True) related_uuid = models.CharField(max_length=22, blank=True) -
mod_wsgi setup in production failed to start
I am deploying a django project in production using ubuntu, and I have been following this tutorial explaining how to setup and run mod_wsgi in production. Upon running apachectl start I get the following error apachectl start AH00526: Syntax error on line 53 of /etc/apache2/sites-enabled/django_project-le-ssl.conf: SSLCertificateFile: file '/etc/letsencrypt/live/www.dimsum.dk/fullchain.pem' does not exist or is empty Action 'start' failed. The Apache error log may have more information. Prior starting the apachectl I did the followings: pip install mod_wsgi The installation was successful and I then put mod_wsgi.server in my INSTALLED_APPS under settings.py. I then run without problem python manage.py runmodwsgi \ --server-root/etc/wsgi-port-80 \ --user www-data --group www-data \ --port 80 --setup-only Then I stopped my current apache2 server by sudo service apache2 stop Followed by /etc/wsgi-port-80/apachectl start and got the error AH00526: Syntax error on line 53 of /etc/apache2/sites-enabled/django_project-le-ssl.conf: SSLCertificateFile: file '/etc/letsencrypt/live/www.dimsum.dk/fullchain.pem' does not exist or is empty Action 'start' failed. The Apache error log may have more information. -
Django Test Client returning error on client.get(reverse('polls:index'))
working through the Django tutorial and running into issues. Patience appreciated! I'm on part 5 attempting to use the test client. When I run: > response = client.get(reverse('polls:index')) I get the following error: TemplateSyntaxError: Invalid block tag on line 38: '<span', expected 'empty' or 'endfor'. Did you forget to register or load this tag? I'm sure it has to do with my index.html or some other file associated with my Django code so please ask me to edit this post with applicable files. For now, here is the index.html code: <meta charset="utf-8"> <title>My test page</title> </head> <body> <h1>subtitle test thing</h1> <p> {% if latest_question_list %} <ul> {% for question in latest_question_list %} <li> <a href=“{% url 'polls:detail' question.id %}”>{{ question.question_text }} </a> </li> {% endfor %} </ul> {% else %} <p>No polls are available.</p> {% endif %} </p> </body> </html> Fair point here: I DO NOT KNOW HTML. I understand that Django provides incomplete HTML so I did my best to build structure around it. I have no idea if it's even right. Other files that might be helpful: urls.py: > from django.urls import path from . import views > > app_name = 'polls' urlpatterns = [ > path('', views.IndexView.as_view(), … -
print Python dictionary in some another way
t = '%(a)s %(b)s %(c)s' print(t % dict(a='Welcome', b='to', c='home')) I have seen the above question in one of my python test but didn't get an idea of what is happening here. Can someone please explain to me what is happening why the print function is printing 'Welcome to home'? -
How do I build a system to view a user's profile contents trough a link
I already have a profile viewing and updating page for user. But I want everyone able to view the users profile through a link in the user's post. views.py: def teacherprofile(request, id): userT = User.objects.filter(id=id) return render(request, 'viewprofile.html', {'posts': userT}) urls.py: urlpatterns = [ path('', views.index, name='index'), path('home', views.index, name='home'), path('signup', views.signup, name='signup'), path('postskill', views.postskill, name='postskill'), path('profile', views.profile, name='profile'), path('teacherprofile/<int:id>',views.teacherprofile, name='teacherprofile'), path('post/<int:id>', views.post, name='post'), path('post_delete/<int:pk>', views.post_delete, name='post_delete') ] home.html template from where the url for teacherprofile is called: {% for a in skills %} <ul> <div class = "rca"> <li>Posted By: <a href="{% url 'teacherprofile' a.id %}"> <h5> {{a.teacher_name}} </h5></a></li> <li>Subject Type: {{a.skill_type}}</li> <li>Subject Name: {{a.name}}</li> <li>Duration: {{a.duration}} months</li> <li>Cost: Rs. {{a.cost}}</li> <li>Location: {{a.location}}</li> </div> </ul> {% endfor %} viewprofile.html template: {% extends "base_generic.html" %} {% load crispy_forms_tags %} {% block content %} <img class="rounded-circle account-img" src="{{posts.image.url}}" height="100" width="100"> <h5> First Name: {{posts.first_name}} </h5> <h5> Last Name: {{posts.last_name}} </h5> <h5> Username: {{posts.username}} </h5> <h5> Email: {{posts.email}} </h5> <p> Bio: {{posts.profile.bio}} </p> {% endblock %} -
Hi, I want to know how to implemente a logic using PayPal in Django :)
I am struggling with the logic, since I want to charge the customer before creating the "Reservacion" instance. So, the code in the view where I have the logic is here: if (Cantidad_Mesas - Mesas_Ocupadas) >= Mesas_a_Ocupar_Cliente: nueva_reservacion = Reservacion.objects.create(Nombre=Nombre, Dia=Dia, Numero_Personas=Numero_Personas, Email=Email, Horario=Horario) # Creamos una instancia del modelo Reservación directamente desde el "view.py". nueva_reservacion.save() # Guardamos la nueva instancia creada en la base de datos. set_ = True # Hacemos uso de esta bandera, para indicar que SÍ fue posible guardar la reservación en la BD. return render(request, "reservacion/disponibilidad_horarios.html", {"disponibilidad": lista_horarios, "dia_reservacion": Dia}) But I want to do is, as I said, before creating the instance "Reservacion", I want to be able to built-in a payment using PayPal, so. Any Ideas? Thank u, so much! -
clients.models.Clients.DoesNotExist: Clients matching query does not exist. - django python
this is how I solve the problem clients.models.Clients.DoesNotExist: Clients matching query does not exist for r in orders_page: try: cls2 = cls.objects.get(related_uuid=r.related_uuid) related_list.append(cls2) except clients.models.Clients.DoesNotExist: pass is there any better solution for get empty? -
Django - account.models.Account doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS while using pinax-notifications
Integrating client project with pinax-notifications for notification kind of functionality. *File "/home/user/Shwetha/ramble/ramble/rambleapp/urls.py", line 56, in <module> url(r"^notifications/", include("pinax.notifications.urls", namespace="pinax_notifications")), File "/home/user/.local/lib/python3.6/site-packages/django/urls/conf.py", line 34, in include urlconf_module = import_module(urlconf_module) File "/usr/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/home/user/.local/lib/python3.6/site-packages/pinax/notifications/urls.py", line 3, in <module> from .views import NoticeSettingsView File "/home/user/.local/lib/python3.6/site-packages/pinax/notifications/views.py", line 5, in <module> from .compat import login_required File "/home/user/.local/lib/python3.6/site-packages/pinax/notifications/compat.py", line 12, in <module> from account.decorators import login_required File "/home/user/.local/lib/python3.6/site-packages/account/decorators.py", line 5, in <module> from account.utils import handle_redirect_to_login File "/home/user/.local/lib/python3.6/site-packages/account/utils.py", line 13, in <module> from .models import PasswordHistory File "/home/user/.local/lib/python3.6/site-packages/account/models.py", line 26, in <module> class Account(models.Model): File "/home/user/.local/lib/python3.6/site-packages/django/db/models/base.py", line 116, in __new__ "INSTALLED_APPS." % (module, name) RuntimeError: Model class account.models.Account doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS.* As per the https://github.com/pinax/pinax-notifications#documentation Documentation , it was installed and configured. Encountered the above error while configuring. Already tried: In settings.py, INSTALLED_APPS section add both pinax and pinax-notifications. Added Sites in INSTALLED_APPS and made SITE_ID=1 in … -
Error accessing Sendinblue (Hosting: Pythonanywhere)
¡Hello! I have recently deployed a website developed in Django to Pythonanywhere. The web is integrated with Sendinblue, I checked the Whitelisted and saw that the API is allowed for free accounts in Pythonanywhere. I ask for your help because all the API queries give me errors like the one I show you at the end, on the other hand everything works fine outside the hosting. I would appreciate if you could tell me what I should do to access the Sendinblue API. Thank you very much to all. Greetings Error: 2021-03-17 11:55:19,469: Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x7fb4274735d0>: Failed to establish a new connection: [Errno 101] Network is unreachable')': /v3/contacts?limit=5&offset=0 -
Django, using select2 for choice field
Now that select2 is shipped in django for the autocomplete_fields feature, I have been looking for a way to use the select2 widget for a simple choice field which has many options. what's the current best way to do so? -
Stop forloop tag template - Django
I am trying to stop a "forloop" tag template in Django, but I couldn't find a way to do that. In my Django template, I want to show all the articles that I have in my database. And each of those articles is connected to one or more SDGs. For now, my code is showing all the related SDGs, but I would like to only show the first result, and thus stop the "forloop" as soon as there is one positive result. Would someone know how to do that? Here is my Django template: <section> <div class="row px-4"> {% for article in articles %} <div class="col-md-12 col-lg-3 px-3 mb-5" data-aos=fade-up> <div class="card shadow lift rounded"> <div class="card-body py-4"> <h3 class="card-title">{{ article.title }}</h3> {% for sdg in sdg_seed_image %} {% if sdg.seed_id == article.id %} <h4>{{ sdg.sdg_id }}</h4> {% endif %} {% endfor %} </div> </div> </div> {% endfor %} </div> </section> Here is my view code: def article_view(request): articles = Article.objects.all().order_by("-date_publication") sdg_seed_image = SDG_Seed.objects.all() return render(request, "dist/inside/article/view_all.html", context={"articles": articles, "sdg_seed_image": sdg_seed_image})