Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to align boxes in horizontal using css
Can anybody tell me how to align these boxes in horizontal. I use loop and getting input using rending url as you can see in screenshot. Can anybody tell me how to print them in horizontal, using css i am doing this in flask also rending the url for getting input so color and box numbers change. -
django, sendGrid not sending mail
I'm trying to send mail using SendGrid on django development server. Here are my setting: EMAIL_HOST = 'smtp.sendgrid.net' DEFAULT_FROM_EMAIL = 'myemail@gmail.com' EMAIL_USE_TLS = True EMAIL_PORT = 587 EMAIL_USE_SSL = False EMAIL_HOST_USER = 'apikey' EMAIL_HOST_PASSWORD = config('PASS') and it is not working, it returns 1 on the terminal and nothing happens. -
Django user log in
In django, i cannot log in even as a superuser on the site but only at the django admin page. same as users created through the site cannot log in after they succesfully signed up. once they log out after signing up, they are not able to log in again. I am expecting all users that signed up to be able to log in even after they log out -
django crispy form does not work in the template
I'm trying to make my form-fields to be in a row like this html code down below, but it does not work, I want all the fields in the PrimryForm class to be in a row not in a column: Html code: <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous"> <div class="container"> <div class="row"> <div class="col"> <div class="form-group"> <input type="text" class="form-control"> </div> </div> <div class="col"> <div class="form-group"> <input type="text" class="form-control"> </div> </div> <div class="col"> <div class="form-group"> <input type="text" class="form-control"> </div> </div> </div> </div> Forms.py file: from crispy_forms.helper import FormHelper from crispy_forms.layout import Layout, Row, Column class PrimaryForms(forms.ModelForm): signature_of_student = JSignatureField( widget=JSignatureWidget( jsignature_attrs={'color':'#e0b642', 'height':'200px'} ) ) signature_of_guardian = JSignatureField( widget=JSignatureWidget( jsignature_attrs={'color':'#e0b642', 'height':'200px'} ) ) date_of_birth = forms.DateField(widget=forms.DateInput(attrs={'type': 'date'})) class Meta: model = Primary fields = ['admission_number', 'profile_picture', 'first_name', 'last_name', 'gender', 'address_of_student', 'class_Of_student', 'comment_of_student', 'year_of_graduation', 'date_of_birth', 'religion', 'mother_name', 'signature_of_student', 'relationship', 'signature_of_guardian'] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_method = 'post' self.helper.form_class = 'form-horizontal' self.helper.label_class = 'col-md-3' self.helper.field_class = 'col-md-9' My Form/template: {% load crispy_forms_tags %} <div class="container"> <div class="row justify-content-center"> <div class="col"> <form method="post" enctype="multipart/form-data"> {% csrf_token %} {% crispy form %} <br> <button type="submit" class="btn btn-primary">Create Student</button> </form> </div> </div> </div> How can I do this using django-crispy-form? -
Django CKEditor RichTextEditorWidget Admin not working
I'm trying to create a textfield with CKEditor >>> from ckeditor.widgets import CKEditorWidget to be able to add notes for every row in the admin and save them. I followed the tutorial on CKeditor docs and its not working. There are no error its just the CKEditorWidget not showing in the textfields. here is my admin.py file: from django import forms from django.contrib import admin from ckeditor.widgets import CKEditorWidget # Register your models here. from .models import Inventory from import_export.admin import ImportExportModelAdmin class InventoryAdminForm(forms.ModelForm): notes = forms.CharField(widget=CKEditorWidget()) class Meta: model = Inventory fields = '__all__' class InventoryAdmin(ImportExportModelAdmin): list_display = ['sku','qty','price','notes'] list_filter = ('sku','qty','price',) search_fields = ('sku','qty','price',) list_editable = ('qty','price','notes') list_max_show_all = True form = InventoryAdminForm admin.site.register(Inventory, InventoryAdmin) the text editor is not showing up. -
Type checking error: views.py:24: error: "HttpRequest" has no attribute "tenant"
I am creating a Django application which is multi-tenanted. The custom middleware I use attaches a tenant object to the request. My issue is when type checking, my views are not aware of extra attribute on the HttpRequest class. I have tried creating a TenantHttpClass which extends HttpRequest and adds the tenant attribute. How do I make my views aware of this. My code is below: middleware/main.py: from typing import Type from django.db import connection from django.http import Http404 from django.utils.deprecation import MiddlewareMixin from apps.tenants.custom_request import TenantHttpRequest as HttpRequest from apps.tenants.models import Domain, Tenant from apps.tenants.utils import get_public_schema_name, get_tenant_domain_model, remove_www from vastdesk import settings class TenantMainMiddleware(MiddlewareMixin): TENANT_NOT_FOUND_EXCEPTION: Type[Http404] = Http404 """ This middleware should be placed at the very top of the middleware stack. Selects the proper database schema using the request host. Can fail in various ways which is better than corrupting or revealing data. """ @staticmethod def hostname_from_request(request: HttpRequest) -> str: """Extracts hostname from request. Used for custom requests filtering. By default removes the request's port and common prefixes. """ return remove_www(request.get_host().split(":")[0]) def get_tenant(self, domain_model: Domain, hostname: str) -> Tenant: domain = domain_model.objects.select_related("tenant").get(domain=hostname) return domain.tenant def process_request(self, request: HttpRequest) -> None: # Connection needs first to be at … -
mail is not sent in django help no se envia mail en django
I try to get an email from my page that I made in django, but it doesn't, I did if it was sent, tell me that it was sent correctly, and if it was not sent, it would redirect me to the same page. The problem is that it is never sent correctly, as if something was wrong directly when I coded the view or something like that. the problem is that it is never sent. the POST is never sent. Views.py from django.shortcuts import render , redirect from .forms import FormularioContacto from django.core.mail import EmailMessage # Create your views here. def contacto(request): formulario_contacto=FormularioContacto() if request.method == "POST": formulario_contacto=FormularioContacto(data=request.POST) if formulario_contacto.is_valid(): nombre= request.POST.get("nombre") email= request.POST.get("email") numero= request.POST.get("numero") contenido= request.POST.get("contenido") email=EmailMessage("mensaje desde app django", "el usuario con el nombre: {} con la direccion: {} y el numero: {} te escribe: \n\n {}".format(nombre, email, numero, contenido), "", ["faustofernandezes@gmail.com"], reply_to=[email]) try: email.send() return redirect("/contacto/?valido") except: return redirect("/contacto/?novalido") return render(request, "contacto/contacto.html" , {'miFormulario' : formulario_contacto}) settings: STATIC_URL = '/static/' MEDIA_URL='/media/' MEDIA_ROOT=BASE_DIR / 'media' # Default primary key field type # https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' #config de mail EMAIL_BACKEND="django.core.mail.backends.smtp.EmailBackend" EMAIL_HOST="smtp.gmail.com" EMAIL_USE_TSL=True EMAIL_PORT=587 EMAIL_HOST_USER="faustofernandezes@gmail.com" EMAIL_HOST_PASSWORD="Here I put my 2-step verification application password" html: {% extends "ProyectoApp/base.html" … -
Choosing the scenario of using Web Sockets in standard HTTP REST API
I will be happy to get advice from more experienced developers about adding Web Sockets into my HTTP-based project. That’s the thing. I have developed the REST API based service. Everything works well enough, but… In some special cases my server needs a long time to serve client requests. It may be from 1 minute to several hours (and even days)! I implement some not-so-good algorithm to address this issue: Client sends HTTP request Server replies about registering request Client starts sending HTTP requests to get necessary data (if response does not have needed information the client sends another request and so on) That is all in a nutshell. And it seems to be a bad scenario and I am trying to integrate web sockets for adding duplex-channels in this architecture. I hope that my API will be able to send info about updated data as soon as possible without the necessity of many requests from the client. But I am a bit confused in choosing one of two ways to use web socket (WS). Variant A. The server only tells the client via WS that data is ready. And the client gets data by standard request-response HTTP method from … -
React/Django application in VSCode is giving me a "syntax" error, but I don't know what it means and never seen it before
I started building the front-end of the application with react and then I integrated Django and Django RF afterwards. I had a couple of problems with the initial set up, but I have been able to figure out each bug as they come, however, this one I don't really know what it means, it looks like a syntax error, but I am not sure what's causing it. When I run the server there's no problems and I actually a 200 status code 200 status code when going to localhost:8000 webpack is running and compiled successfully In my index.html I am trying yo load my JS which is in a static folder like this enter image description here but it shows me sort of like a syntax error, maybe it's not expecting that type of syntax ? When I look at my console in the browser I can see that my links have loaded, and that the script is working since it can reference where my JS file is console in the browser index.js import file problems One way to fix this is by adding type="module" in my index.html file inside the script tag, but once I do that it gives … -
How can I solve the reportMissingModuleSource by using Django and docker-compose without creating a virtual environment?
I've tried to create a new project with Django and docker-compose without creating virtual environment. But now, when I want to start coding in VS Code, I get the reportMissingModuleSource. For example in mysite/urls.py "Import "django.contrib" could not be resolved from sourcePylance" I'm trying to search more to find a solution! -
What is the best index for a "last modified by user" query
I have a Django query like Posts.objects.filter(user=user).order_by('-last_modified') What is the best type of index to support this query? I see two options: Index(fields=['user_id', '-last_modified']) Index(fields=['-last_modified']) Given that Django automatically indexes foreign keys such as user_id, is there any benefit to 1) vs 2)? It seems like 1) would result in fewer items being traversed by the DB, but maybe DBs are "smart enough" to join two separate indexes together and as a result the advantage will be minimal. My question is theoretical in nature: which index is the better option, in principle? -
raise ImproperlyConfigured(msg)
raise ImproperlyConfigured(msg) In "additional_app", in "models.py": from django.db import models from django.contrib.auth import get_user_model User = get_user_model() class Profile(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) id_user = models.IntegerField() bio = models.TextField(max_length=500, blank=True) profileimg = models.ImageField(upload_to='profile_images', default='btm-banner.png') location = models.CharField(max_length=100, blank=True) def __str__(self): return self.user.username I have created 'media_folder' in "additional_app" and put into img 'btm-banner.png' to django load it if user dont load self picture in profile. Also i write in settings.py: MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') Also in 'main_app', in urls.py: from django.conf import settings from django.conf.urls.static import static urlpatterns = urlpatterns + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Now i want make 'migration' In Terminal: S:\Programms\Projects\social_app\main_app> py manage.py makemigration Enter Result: django.core.exceptions.ImproperlyConfigured: additional_app.apps.AdditionalAppConfig.default_auto_field refers to the module 'django.db.media .BigAutoField' that could not be imported. -
JWT cookie from Django backend not working after deploy
I have written a web app, the backend is in Django using django_rest_framework utils and the frontend is in React.js An authentication is based on JWT token stored in cookies and localStorage. It was working fine when both sides were on the localhost, but after I deployed frontend and backend on the remote server, a Django cannot set cookie in the frontend domain. Here's my code from LoginView in Django: `class LoginView(APIView): def post(self, request): username = request.data['login'] password = request.data['password'] user = authenticate(username=username, password=password) if user is not None: payload = { 'id': user.id, 'username': user.username, 'exp': datetime.datetime.utcnow() + datetime.timedelta(minutes=3600), 'iat': datetime.datetime.utcnow() } token = jwt.encode(payload, 'secret', algorithm='HS256') response = Response() response.set_cookie(key='jwt', value=token, httponly=False) response.data = { 'jwt': token, 'username': user.username, 'userId': user.id } return response response = JsonResponse({"message": "An issue occured during the authentication process."}) response.status_code = 500 return response` settings.py CORS_ORIGIN_WHITELIST = [ ... 'https://<MY FRONTEND>.azurewebsites.net' ... ] CSRF_TRUSTED_ORIGINS = [ ... "https://<MY FRONTEND>.azurewebsites.net" ] CORS_ALLOWED_ORIGINS = [ ... "https://<MY FRONTEND>.azurewebsites.net" ] CORS_ALLOW_CREDENTIALS = True CSRF_USE_SESSIONS = False SESSION_COOKIE_SECURE = False CSRF_COOKIE_SECURE = False CSRF_COOKIE_SAMESITE = 'None' SESSION_COOKIE_SAMESITE = 'None' SESSION_COOKIE_DOMAIN = '.azurewebsites.net' CORS_ALLOW_HEADERS = list(default_headers) + ['Set-Cookie'] After logging in on my frontend app, I cannot … -
Simplify function code while maintaining readability
This code works, but seems too redundant to me. Is it possible to somehow simplify it while maintaining functionality and readability? has_videos = self.request.query_params.get('has_videos') if has_videos: if has_videos == 'true': entries = User.objects.filter(videos__isnull=False) elif has_videos == 'false': entries = User.objects.filter(videos__isnull=True) else: entries = User.objects.all() I tried to write in one line using the ternary operator, but the readability disappeared completely entries = Pet.objects.all() if has_photos not in ['true', 'false'] \ else Pet.objects.filter(photos__isnull=False) if has_photos == 'true' \ else Pet.objects.filter(photos__isnull=True) -
AttributeError at type object 'Services' has no attribute 'app'
I newly started to develop Django. I want to connect my python algorithm and Django web ui so I tried to connect both of them in views.py but I encountered a problem. It says AttributeError at type object 'Services' has no attribute 'app' but I declared it in the queryOnMetadataModel.init. I don't know what is wrong. Could someone help me? These are my code snippets; queryOnMetadataModel.py from Neo4jConnection import App import json class Services:` def __init__(self): uri = "neo4j+s://a50f760a.databases.neo4j.io:7687" user = "neo4j" password = "password" self.app = App(uri, user, password) def find_node_type(self,nodeName): node_type = self.app.find_node_type(nodeName) self.app.close() return node_type views.py from django.shortcuts import render from BitirmeTeziSourceCode.queryOnMetadataModel import Services import sys sys.path.append(".") # Create your views here. def home(request): data = Services.find_node_type(Services , 'Region') nodes = { "nodes" : data } return render(request , "index.html" , nodes) urls.py from django.urls import path from . import views urlpatterns = [ path("" , views.home) ] Error Image I want to access output of Services.find_node_type(Services , 'Region') from index.html -
Django - Receive Webhooks from WhatsApp Cloud Api
I'm trying to create a chat application with the WhatsApp Cloud API and I'm stuck on how to handle webhooks. Should I do it with websockets or is there another way to do it? I already tried with django-channels but I don't know how to receive the webhooks. If django-channels is the best option, could you tell me how I can receive the webhooks or point me to a tutorial. Currently I already have the sockets implemented and they connect without problems from channels.generic.websocket import JsonWebsocketConsumer class ChatConsumer(JsonWebsocketConsumer): """ This consumer is used to show user's online status, and send notifications. """ def __init__(self, *args, **kwargs): super().__init__(args, kwargs) self.room_name = None def connect(self): print("Connected!") self.room_name = "home" self.accept() self.send_json( { "type": "welcome_message", "message": "Hey there! You've successfully connected!", } ) def disconnect(self, code): print("Disconnected!") return super().disconnect(code) def receive_json(self, content, **kwargs): print(content) return super().receive_json(content, **kwargs) -
Django: After saving the Order and deleting the cart, Order looses information of ordered items
I want the cart items to be saved in each order. But after the cart is deleted, "service_items" becomes empty. Steps: Add items to the cart Save order Delete cart I think service_items = models.ManyToManyField(Cart) is causing the issue, but I don't know how to fix it. Current Order object after saving: { "id": 1, "customer": { "id": 1, "first_name": "Some", "last_name": "User", "email": "someuser@gmail.com", "phone_number": "+817056781234", "member_date": "2023-01-28T14:38:43.196580Z" }, "status": false, "total": "15.00", "order_date": "2023-01-28T16:05:11.704636Z", "delivery_date": "2023-01-31T12:52:16.193078Z", "advance_payment": "9.00", "payment_method": "cash", "due_payment": 6.0, "service_items": [] } Expected outcome: { "id": 1, "customer": { "id": 1, "first_name": "Some", "last_name": "User", "email": "someuser@gmail.com", "phone_number": "+817056781234", "member_date": "2023-01-28T14:38:43.196580Z" }, "status": false, "total": "15.00", "order_date": "2023-01-28T16:05:11.704636Z", "delivery_date": "2023-01-31T12:52:16.193078Z", "advance_payment": "9.00", "payment_method": "cash", "due_payment": 6.0, "service_items": [ { "id": 1, "service_item": { "id": 1, "item_name": "Black Shirt", "description": "Half and Full Sleeve Black Shirts.", "wash_price": "3.00", "stain_treatment_price": "1.00", "iron_price": "2.00", "dry_wash_price": "4.00", "category": { "id": 2, "title": "Shirt" } }, "is_wash": false, "is_stain_treatment": true, "is_iron": false, "is_dry_wash": true, "quantity": 3, "unit_price": "5.00", "price": "15.00", "customer": 1 } ] } models.py class ServiceItem(models.Model): item_name = models.CharField(max_length=200) description = models.TextField(null=True) wash_price = models.DecimalField(max_digits=6, decimal_places=2, null=False, default=0) stain_treatment_price = models.DecimalField(max_digits=6, decimal_places=2, null=False, default=0) iron_price = models.DecimalField(max_digits=6, decimal_places=2, … -
Django: subtract the total from two table group by common group name
I'm trying to get the result from exchange table (incoming) (-) expense table grouped by account but the result is multiplying the Sum * the number of rows in the other table. class Account(models.Model): trip = models.ForeignKey(Trip, default=1, on_delete=models.SET_DEFAULT) description = models.CharField('Description', max_length=254) class Exchange(models.Model): buy_date = models.DateField(verbose_name='Buy Date') quantity = models.DecimalField(('Quantity'), max_digits=32, decimal_places=2, blank=True, null=True) quote = models.DecimalField(('Quote'), max_digits=32, decimal_places=2, blank=True, null=True) total = models.DecimalField(('Total'), max_digits=32, decimal_places=2, blank=True, null=True) account = models.ForeignKey(Account, default=1, on_delete=models.SET_DEFAULT) class Expense(models.Model): start_date = models.DateTimeField(verbose_name='Date') amount = models.DecimalField(('Amount'), max_digits=32, decimal_places=2, blank=True, null=True) fee = models.DecimalField(('Fee'), max_digits=32, decimal_places=2, blank=True, null=True, default=0) total = models.DecimalField(('Total'), max_digits=32, decimal_places=2, blank=True, null=True, default=0) account = models.ForeignKey(Account, default=1, on_delete=models.SET_DEFAULT) I've tried to perform the following operation: result = ( Account .objects .values('description') .filter(created_by=user) .filter(trip=selectedtrip_id) .filter(exchange__quantity__gt=0) .annotate(exchange_total=Sum('exchange__quantity'), expense_total=Sum('expense__total') ) .annotate(account_remain=F('exchange_total') - F('expense_total')) .order_by('description') ) The idea is to know how much left on the account. But the problem is when you do the operation like this, the result is the total multiplied by the number of rows on the expense table. Account 1,Account01 2,Account02 Exchange 2023-01-01, 100, 5.0, 500, 1 2023-01-01, 100, 4.9, 490, 1 2023-01-01, 200, 5.1, 510, 1 2023-01-01, 100, 5.0, 500, 2 Expense 2023-01-10, 10, 1, 11, 1 2023-01-11, … -
Getting SSL error when sending mail via Django
[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:997) This is what I see when I send mail via Django. This is my email configuration in settings.py # Email Settings EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend" EMAIL_HOST = "smtp.gmail.com" EMAIL_PORT = 587 EMAIL_HOST_USER = "xxxxxxxx@gmail.com" EMAIL_HOST_PASSWORD = "xxxxxxxxxxxxx" EMAIL_USE_TLS = True this is how I send mail send_mail( "Subject", "Test message", settings.EMAIL_HOST_USER, ["xxxxxxxxx@gmail.com"], fail_silently=False, ) -
Django filter queryset and get unique items
I am using Django and SqLite. I have this model table: class TestPROD(models.Model): prodID = models.CharField(max_length=15) ProdDate = models.CharField(max_length=15) Price1 = models.DecimalField(max_digits=10, decimal_places=3,default=0) Price2 = models.DecimalField(max_digits=10, decimal_places=3,default=0) post_date = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User,on_delete=models.CASCADE) def __str__(self): return self.prodID def get_Total(self): TotPRC =self.Price1 +self.Price2 return round(TotPRC, 2) def get_absolute_url(self): return reverse('Custom', args=[self.prodID]) class Meta: ordering = ('-TestDate',) in my data base I have many rows which contains duplicated items for example prodID HP or Lenovo have 1000 or more rows. my question is how to filter the data and give me only the last ProdDate of the product HP and so the last item for Lenovo and one. in my views.py I tried many solution but I din't get the good results def welltests(request): testprodms = TestPROD.objects.annotate(latest_test_date=('prodID')).order_by('-ProdDate').distinct() return render(request, 'Home/AllProd.html', {'testprodms': testprodms}) this will gives my all the data (50000 rows) but organized by product. the unique prodID in my database is about 600. so I need 600 rows of different product with the last ProdDate then I tried this and many other but not working; def welltests(request): testprodms = TestPROD.objects.order_by().values_list('prodID', flat=True).distinct() return render(request, 'Home/AllProd.html', {'testprodms': testprodms}) this gives me the number of my products but with no other data in my … -
i want create url when user click pass to profile page -- NoReverseMatch at /home
i want create url when user click pass to profile page ++++ models class profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) music = models.CharField(max_length=50) skils = models.CharField(max_length=50) search = models.CharField(max_length=50) posts = models.CharField(max_length=50) boi = models.TextField() img = models.ImageField(upload_to="profile-img") def __str__(self): #return self.user or 'User' return str(self.id) def create_profile(sender, **kwargs): if kwargs['created']: user_profile = profile.objects.create(user=kwargs['instance']) post_save.connect(create_profile, sender=User) +++ views def home(request): return render(request, 'main-frond.html') def profile_edit(request, id): pro_edit = profile.objects.get(id=id) if request.method == 'POST': user_form = User_Form(request.POST, request.FILES, instance=pro_edit) if user_form.is_valid(): user_form.save() return redirect('profile_views') else: user_form = User_Form(instance=pro_edit) context = {'user_form' : user_form} return render(request, 'profile_edit.html', context) +++url path('home', views.home, name="home"), path('profile/<int:id>/edit', views.profile_edit, name="profile_edit") +++ html <a href="{% url 'profile_views' %}">profile</a> django give me problem Reverse for 'profile_views' with no arguments not found. 1 pattern(s) tried: ['profile/(?P<id>[0-9]+)\\Z'] i want create url when user click pass to profile page -
preserve multiple GET parameters in Django URL
In my django project I have a page displaying a list of times. On this page there is 3 GET forms which are for: Parsing through pages Selecting graph data Sorting items If a user is to select a field in all of these forms the URL should look something like this: http://127.0.0.1:8000/watchlist/?page=1&graph_data=price&sort=quantity_desc But when a user submits one of these forms it only saves that GET parameter in the URL. eg: selects page = 2 http://127.0.0.1:8000/watchlist/?page=2 selects sort = quantity_asc http://127.0.0.1:8000/watchlist/?sort=quantity_asc The page parameter is over written when both parameters should be present in the URL. How can i preserve multiple GET parameters in the URL? views.py def watchlist(request): #get requests graph_metric = request.GET.get("graph-data-options", "avg_price") page = int(request.GET.get("page", 1)) sort_field = request.GET.get("sort-field", "avg_price-asc") return render(request, "App/watchlist.html", context=context) html <!-- Page number --> <form id="page-buttons-form" action="{% url 'watchlist' %}" method="GET"> {% for page_button in num_pages %} <input name="page" type="submit" value="{{page_button}}"> {% endfor %} </form> <!-- Sort items --> <form id="sort-form" action="{% url 'watchlist' %}" method="GET"> <label for="sort-field">Sort:</label> <select onchange="this.form.submit()" name="sort-field"> {% for sort in sort_options %} <option value="{{sort.value}}">{{sort.text}}</option> {% endfor %} </select> </form> <!-- Graph data --> <form action="{% url 'watchlist' %}" method="GET"> <label for="graph-data-options">Graph Data</label> <select onchange="this.form.submit()" name="graph-data-options"> {% … -
Django Template doesn't work with a for loop in range. Why?
VIEWS.PY def index(request): posts = Post.objects.all() posts_quantity = range(1) return render(request, 'index.html', {'posts':posts, 'posts_quantity':posts_quantity}) HTML {% for index in posts_quantity %} <a href = "{% url 'architectural_post' posts.index.slug %}" class = "post"> {% endfor %} it gives me an error: Reverse for 'architectural_post' with arguments '('',)' not found. But everything works well if I put 0 instead of index, like this (just for debugging): {% for index in posts_quantity %} <a href = "{% url 'architectural_post' posts.0.slug %}" class = "post"> {% endfor %} Why and how to fix it? Thanks. -
Why django forms shows input in row instead of a column
I wonder why django modelForm shows input in a row instead of a column like this: I like all input in my model to be in a column when putting {{ form|crispy}} in the template, as you can see in the template, even if add col-md-3 to resize the input in a col it does not work, I think there is something I need to know about django-forms. template: --- Bootstrap-5 <div class="container"> <div class="row justify-content-center"> <div class="col-md-3"> <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form|crispy}} <button type="submit" class="btn btn-primary">Create Student</button> </form> </div> </div> </div> The Result: My Forms.py file: class PrimaryForms(forms.ModelForm): signature_of_student = JSignatureField( widget=JSignatureWidget( jsignature_attrs={'color':'#e0b642', 'height':'200px'} ) ) signature_of_guardian = JSignatureField( widget=JSignatureWidget( jsignature_attrs={'color':'#e0b642', 'height':'200px'} ) ) date_of_birth = forms.DateField(widget=forms.DateInput(attrs={'type': 'date'})) class Meta: model = Primary fields = ['admission_number', 'profile_picture', 'first_name', 'last_name', 'gender', 'address_of_student', 'class_Of_student', 'comment_of_student', 'year_of_graduation', 'date_of_birth', 'religion', 'mother_name',] How can I make my input to be in column? -
Javascript returns the same id for every iterated element in html
I have website which i build using Django where every visitor can leave their message or press a like button on any comment. I would like to show how many of a comment has been liked by the user. As each comment is unique, I think to access the comment_id attribute which I wrote in the html part. I then use a simple js function to retrieve the id. The problem is, although html is showing unique id for each comment, Javascript still return the same id, that is the id of the first comment that is written on the page. Can someone tell me where is my mistake in this case? Thank you in advance for your help. my code in js: function likeButton(){ let el = document.getElementById("chat-icon-thumbsup") alert(el.attributes["comment_id"].value) }; my html code, which is looping the datatable records "comment" from a datatable in Django framework: {% for comment_ in comments %} <strong> {{ comment_.name }} - {{ comment_.date_added }} <button><i comment_id="{{ comment_.comment_id }}" id="chat-icon-thumbsup" class="fa fa-fw fa-thumbs-up" title="like this comment" onclick="likeButton()"></i></button> {{ comment_.nr_of_likes }} <br/> </strong> {{ comment_.body }} <br/> {% endfor %} image 1: here you see when I inspect the DOM elements, it retrieves different "comment_id" …