Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Please what should I do?
Here is the traceback, I need help please Environment: Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 3.2.14 Python Version: 3.10.9 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'rest_framework', 'publications', 'django_extensions', 'corsheaders', 'users', 'api', 'thumbnails', 'rest_framework.authtoken', 'dj_rest_auth', 'dj_rest_auth.registration', 'auth.tasks', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.google', 'allauth.socialaccount.providers.apple', 'huey.contrib.djhuey', 'django_filters'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.cache.UpdateCacheMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.cache.FetchFromCacheMiddleware', 'corsheaders.middleware.CorsMiddleware'] Traceback (most recent call last): File "C:\Users\hendri3x22\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\hendri3x22\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\django\utils\deprecation.py", line 116, in call response = self.process_request(request) File "C:\Users\hendri3x22\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\django\middleware\cache.py", line 145, in process_request cache_key = get_cache_key(request, self.key_prefix, 'GET', cache=self.cache) File "C:\Users\hendri3x22\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\django\utils\cache.py", line 362, in get_cache_key headerlist = cache.get(cache_key) File "C:\Users\hendri3x22\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\django_redis\cache.py", line 91, in get value = self._get(key, default, version, client) File "C:\Users\hendri3x22\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\django_redis\cache.py", line 31, in _decorator return method(self, *args, **kwargs) File "C:\Users\hendri3x22\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\django_redis\cache.py", line 98, in _get return self.client.get(key, default=default, version=version, client=client) File "C:\Users\hendri3x22\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\django_redis\client\default.py", line 253, in get client = self.get_client(write=False) File "C:\Users\hendri3x22\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\django_redis\client\default.py", line 105, in get_client self._clients[index] = self.connect(index) File "C:\Users\hendri3x22\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\django_redis\client\default.py", line 118, in connect return self.connection_factory.connect(self._server[index]) File "C:\Users\hendri3x22\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\django_redis\pool.py", line 72, in connect connection = self.get_connection(params) File "C:\Users\hendri3x22\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\django_redis\pool.py", line 91, in get_connection pool = self.get_or_create_connection_pool(params) File "C:\Users\hendri3x22\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\django_redis\pool.py", line 112, in get_or_create_connection_pool self._pools[key] = self.get_connection_pool(params) File "C:\Users\hendri3x22\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\django_redis\pool.py", line 125, in get_connection_pool pool = self.pool_cls.from_url(**cp_params) … -
Running Django Server
I need help tried to run server for Django and got this error, The included URLconf '<module 'myapp.urls' from 'C:\Users\user\Documents\Django Tutorial\myproject\myapp\urls.py'>' does not appear to have any patterns in it. If you see the 'urlpatterns' variable with valid patterns in the file then the issue is probably caused by a circular import. for urls.py in myproject is: ` from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('myapp.urls')), ]` for myapp views.py is: from django.shortcuts import render from django.http import HttpResponse def index(request): return HttpResponse('hello') For myapp urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), ] -
In Django, when trying to access a model's 1:1 relation that doesn't exist, sometime that relation is None, and sometimes it raises an exception. Why?
I noticed while debugging a Django application that with two tables with a 1:1 relation, trying to access the related object from the table that defines the 1:1 relation would return None, while trying to access the same nonexistent relation from the table that does not define the relation Django will raise a Model1.model2.RelatedObjectDoesNotExist exception. I was confused by this behavior as the same action has two different results on objects on the same type of relation. This is an example of the models used: class RelatedModel(models.Model): pass class RelationshipDefiner(models.Model): related_object = models.OneToOneField( RelatedModel, on_delete=models.CASCADE, related_name="relationship_definer", blank=True, null=True ) This is an example of trying to print the relations to screen: relationship_definer = RelationshipDefiner.objects.create() related_object = RelatedModel.objects.create() print("RELATIONSHIP DEFINER'S RELATED OBJECT:") print(relationship_definer.related_object) print("RELATED OBJECT'S RELATIONSHIP DEFINER:") print(related_object.relationship_definer) And the output: RELATIONSHIP DEFINER'S RELATED OBJECT: None RELATED OBJECT'S RELATIONSHIP DEFINER: Internal Server Error: /test/ File "/django/app/views/test.py", line 17, in test print(related_object.relationship_definer) app.models.sample.RelatedModel.relationship_definer.RelatedObjectDoesNotExist: RelatedModel has no relationship_definer. Why do 1:1 nullable relationships behave differently on either side of the relation, and is there a way to coerce Django to behave consistently across both sides of the relationship? -
Styling a GeoDjango widget with TailwindCSS
I have been trying to style the GeoDjango OSMWidget (for Polygon drawing) for ages but can't work out how to make it flexible. Setting the map width and map height is all fine for a fixed page size but what happens if someone snaps their browser window to half-screen? A fixed map width does not react to these changes and becomes an unwieldily feature so fast it's painful. Here is what the GeoDjango documentation suggests for widget styling: widgets = { 'geometry': forms.OSMWidget(attrs={ 'map_width': 1000, 'map_height': 400, 'default_zoom': 7.5 }), } Other widgets, such as forms.Select have the option for a style attribute where custom css can be defined. The map widgets ignore this completely. How can I force this map widget to respond to my css demands? I want flexible widgets, goddamit! *Bonus points for integration with tailwind -
How to automatically connect a logged in User to submit a document
Please I am new to coding, I am currently working on an app where there are various users trying to submit a document, I want them to be able to view only the documents they upload, while the admin can view all the users' documents. I was able to accomplish this but in this case the user field is a foreign key at the backend, and it's showing a drop down on the front end, I want each user to be automatically assigned to theirs, please how do I accomplish this. This is the model.py class Report(models.Model): user = models.ForeignKey(User, null=True, blank=True, on_delete=models.CASCADE) name = models.ForeignKey(Staff, null=True, on_delete=models.SET_NULL) reportname = models.CharField(max_length=200, null=True) date = models.DateTimeField(auto_now_add=True, null=True) report=models.FileField(upload_to='pdf/') def __str__(self): return self.reportname the view.py @login_required(login_url='loginpage') def report (request): if request.method == 'POST': form = ReportForm(request.POST, request.FILES) if form.is_valid(): form.user = request.user form.save() # Redirect to the document list after POST messages.info(request,'Submitted Sucessfully') return redirect('submitted_report') else: form = ReportForm() # A empty, unbound form return render(request,'report.html',{ 'form':form,'repor':report } ) @login_required(login_url='loginpage') def submitted_report(request): report = Report.objects.filter(user=request.user) return render(request,'submitted_report.html',{ 'report': report }) -
Django, TemplateSyntaxError at. Help me
I am doing a website by Django, but I have a registor problem, which I don't know how to solve,help me).Before last change, everything was working, but I have changed only this files: views.py from django.http import HttpResponse, HttpResponseRedirect, HttpResponsePermanentRedirect from django.shortcuts import render from django.http import * from django.template.response import TemplateResponse def index(request): cat = ["Cars", "Plates", "Fruits", "Phones", "Bananas"] return render(request, "firstapp/index.html", context={"cat": cat}) def about(request): return HttpResponse("About") def contact(request): return HttpResponseRedirect("/about") def details(request): return HttpResponsePermanentRedirect("/") index.html {% extends "firstapp/base.html" %} {% block title %}Index{% endblock title %} {% block header %}Main page{% endblock header %} {% block content%) <p>Types of products</p> {% for i in cat %} <li>{{ i }}</li> {% endfor %} {% endblock content %} and I got this problem: Invalid block tag on line 9: 'endblock'. Did you forget to register or load this tag? 1 {% extends "firstapp/base.html" %} 2 {% block title %}Index{% endblock title %} 3 {% block header %}Main page{% endblock header %} 4 {% block content%) 5 <p>Types of products</p> 6 {% for i in cat %} 7 <li>{{ i }}</li> 8 {% endfor %} 9 {% endblock content %} I don't know what to do in this case, … -
Error passing jinga url template to javascript function
I am trying to run the following javascript function <script> function getForm(id, element, url_route) { console.log(id, element, url_route) } </script> within <a href="javascript:void(0)" onclick="getForm('login-form', 'login-authentication', '{% url 'accounts:password_reset' %}');">Login</a> Clearly there is a problem with the quotations in '{% url 'accounts:password_reset' %}'. I have tried various different approaches to escape the quotations but the webserver still throws out an error. I have tried the following but still unsuccessful: <a href="javascript:void(0)" onclick="getForm('login-form', 'login-authentication', '{% url \'accounts:password_reset\' %}');">Login</a> <a href="javascript:void(0)" onclick="getForm('login-form', 'login-authentication', '{% url &quot;accounts:password_reset&quot; %}');">Login</a> I have also tried to build the url directly from the javascript function but it also doesn't work. var url = 'accounts:password_reset'; console.log('{% url "' + url + '" %}'); -
Pass capitalised variables to django settings.configure()
I am looking for a way to read from a list of variables and set them in Django settings using the settings.configure() method: from django.conf import settings def func(i): # do something and return for item in items: settings.configure(item=func(item)) But have no idea how I could write this properly to get past the TypeError: Setting 'item' must be uppercase. -
How to indicate required fields on initial form render, using Bootstrap 5 styling and Django?
I am using Django 4.1 and Bootstrap 5. I think I'd like to mark required fields in a form as required, or maybe optional fields as optional, as suggested in this question. Django/Bootstrap already styles fields as green/red after form submission, if a required field is missing, but my request is when the form is first rendered. Could be with *s or with "(optional)" or whatever. What's the best way to do it? -
CrispyError at /account/register |as_crispy_field got passed an invalid or inexistent field
I need help to fix this. Error during template rendering In template /*/dev/ecommerce/account/templates/account/registration/register.html, error at line 45 |as_crispy_field got passed an invalid or inexistent field 35 36 <h5> Purchase your favourite items today! </h5> 37 38 <hr> 39 <br> 40 41 <form method="POST" autocomplete="off"> 42 43 {% csrf_token %} 44 45 {{form.username|as_crispy_field}} 46 47 <br> <br> 48 49 50 {{form.email|as_crispy_field}} 51 52 <br> <br> 53 54 55 {{form.password1|as_crispy_field}} -
Get Session for Forms in Django
I'm working on a single page to handle all stufs related to accounts such as login/register. For that i'm using a CBV with a multiforms.py that do the get,post,validations etc. I'm having a problem with the login form, that is saying 'LoginForm' object has no attribute 'session' current error Here are the multiforms.py `class ProcessMultipleFormsView(ProcessFormView): def get(self, request, *args, **kwargs): form_classes = self.get_form_classes() forms = self.get_forms(form_classes) return self.render_to_response(self.get_context_data(forms=forms)) def post(self, request, *args, **kwargs): form_classes = self.get_form_classes() form_name = request.POST.get('action') if self._individual_exists(form_name): return self._process_individual_form(form_name, form_classes) elif self._group_exists(form_name): return self._process_grouped_forms(form_name,form_classes) else: return self._process_all_forms(form_classes) def _individual_exists(self, form_name): return form_name in self.form_classes def _group_exists(self, group_name): return group_name in self.grouped_forms def _process_individual_form(self, form_name, form_classes): forms = self.get_forms(form_classes, (form_name,)) form = forms.get(form_name) if not form: return HttpResponseForbidden() elif form.is_valid(): return self.forms_valid(forms, form_name) else: return self.forms_invalid(forms)` my LoginForm ` class LoginForm(MultipleForm,forms.Form): email = forms.EmailField(max_length = 60) password = forms.CharField(widget=forms.PasswordInput())` and the views.py ` def login_valid(self,request): user = authenticate(email=request.data.get('email'),password=request.data.get('password')) if user is not None: login(request,user) return HttpResponseRedirect(self.get_success_url('login')) else: return render(request,'accounts/login.html')` i already tried alot stufs but still dont get why this error is happening -
ModelForm saving value of submit button to database
I have a form in my project that just wouldnt grab whatever the user typed in and im stumped for why no matter what i typed into the input field, the string 'Post' is what gets saved into the database, which is the value of the submit button, nd whatever i changed the value to is also what gets saved. model class Post(models.Model): post = models.TextField(max_length=250) author = models.CharField(max_length=64) date_time = models.DateTimeField(default=timezone.now, blank=True) def __str__(self): return f"{self.author}, {self.date_time}, {self.post}" form class NewPostForm(ModelForm): class Meta: model = Post fields = ['post'] views.py def index(request): newpostform = NewPostForm() if request.user.is_authenticated: username = request.user.get_username() if request.method == 'POST': post = Post(author=username) newpostform = NewPostForm(request.POST,request.FILES, instance=post) if newpostform.is_valid(): post = newpostform.save() return render(request, "network/index.html") return render(request, "network/index.html", { "newpostform": newpostform }) html > <form action="{% url 'index' %}" method="post"> > {% csrf_token %} > <div> > {{ newpostform }} > </div> > <input id='post-btn' class="btn btn-primary" name="post" type="submit" value="Post"> > </form> -
How to get task status from django-celery-results using task id?
I want to implement celery on a django app. I have used django_celery_results to store task results. celery.py import os from celery import Celery os.environ.setdefault("DJANGO_SETTINGS_MODULE", "coutoEditor.settings") app = Celery("coutoEditor") app.config_from_object("django.conf:settings", namespace="CELERY") app.autodiscover_tasks() settings.py CELERY_BROKER_URL = "redis://localhost:6379" CELERY_RESULT_BACKEND = "django-db" CELERY_RESULT_EXTENDED = True tasks.py @shared_task() def speed_up_vid_task(input_path, speed_factor, start, end): ''' Method Params: input_path: The video file url or directory path file name speed_factor: The factor for the speed up process start: start of the video part that needs to be sped up (in secs) end: end of the video part that needs to be sped up (in secs) ''' start = convert_to_sec(start) end = convert_to_sec(end) filename = str(uuid.uuid4()) print(filename, "new") temporary_dir = BASE_DIR + '/' + editor_speedUp_temp_dir # editor_temp_dir = media/editor/speed_vid/temp/" output_dir = BASE_DIR + '/' + editor_speedUp_output_dir # editor_speedUp_output_dir = media/editor/speed_vid/ # Check for broken url r = requests.get(input_path, stream=True) if not r.status_code == 200: return Response({ 'message': "media file is corrupted", 'data': "broken url process could not be completed", 'status': False }, status=status.HTTP_400_BAD_REQUEST) if not os.path.exists(output_dir): os.mkdir(output_dir) if not os.path.exists(temporary_dir): os.mkdir(temporary_dir) stream = os.popen( "ffmpeg.ffprobe -loglevel error -select_streams a -show_entries stream=codec_type -of csv=p=0 '{}'".format( input_path)) output = stream.read() if len(output) == 0: input_path_vid = os.path.join(BASE_DIR, temporary_dir) + filename … -
CSRF verification Failed in Firebase and Django integration
I am trying to integrate django and DRF with firebase real-time database and while creating a post request I ran into a CSRF verification error. CSRF verification failed. Request aborted. Some solutions I found online said that I should use render but I am actually using Django Rest Framework and would like to use something that works with JsonResponse and Serializers. Here's a test code. def post(self, request): """Function to handle post requests Args: request (_type_): _description_ """ # Get the data to be posted from the request name = request.POST.get('name') age = request.POST.get('age') location = request.POST.get('location') # Set the reference to the database ref = db.reference('/user1') # Push the data to the database ref.push({ 'Name': name, 'Age': age, 'Location': location }) Let me know if I should share how I am creating my firebase client, although I don't think that would be necessary. In conclusion, I would like to find a way to add a csrf_token to a post request method in Django and DRF. Another solution I saw used csrf_exempt but I don't want to use that either as that is not ideal. I do plan on taking this to production at some point so do recommend solutions … -
How to modify objects in django ListView?
I have a ListView for a blog with fields of "title" and "text". How to change "text" for example I want to summarize it something like text[:100] I don't want to change the database. I think the solution is modifying get_queryset but don't know how to implement it. -
Docker-Compose Network Issue on Ubuntu 22.04 LTS
I've been developing my python application using Django with PostgreSQL and Nginx and Docker, driven by Docker-Compose on my Macbook M1. And recently, decided to deploy it on the remote server, which has Ubuntu 22.04 LTS, but encountered really weird issue. My web application says, that it cannot resolve host postgresql (service at docker-compose file, which you can find down below), however, it works fine on my machine, can it be related to the Docker? It might be because I installed imcompatible versions of Docker and Docker-compose on this remote server or apparently used wrong commands, but not really sure about that, as I haven't gained enough experience of working with Ubuntu yet. My Macbook's M1 Docker & Docker-compose Versions: ~ Docker - 20.10.12 ~ Docker-Compose - 1.29.2 My Remote's Server Ubuntu Docker & Docker-compose Versions: ~ Docker - 20.10.23 ~ Docker-compose - 1.29.2 My docker-compose.yaml file version: "3.9" services: nginx_server: container_name: "nginx_web_server" image: crazycoderrr/vdnh_nginx_server:latest # образ nginx для нашего проекта ports: - "8010:80" depends_on: - application_service volumes: - ./nginx/nginx.conf:/etc/nginx/nginx.conf networks: - private_network application_service: container_name: "application_server" image: crazycoderrr/vdnh_application:latest # образ backend сервиса нашего приложения ports: - "8000:8000" depends_on: - postgresql env_file: ./env/application.env networks: - private_network postgresql: container_name: "postgresql_database" image: crazycoderrr/vdnh_postgres_db:latest … -
How to override the autocomplete view for a specific model field in the Django admin?
I need to override the way a Select2 widget of a particular ForeignKey is behaving in the Django (4.1) admin. Namely, I am trying to increase the number of objects returned by the AJAX requests and defined by paginate_by in AutocompleteJsonView. Sadly this great solution no longer works with Django 4. How can I extend AutocompleteJsonView and somehow tell Django to use my custom view? -
How to integrate Fast API and Django
I wanna to write e-commerce website on django. My project will have two DBs: PostgreSQL (For storing users data, django tables, orders handling etc) MongoDB (For storing Products and their categories) Django works well with Relational DBs, but working with NoSQL DBs in Django it's so painfully. FastAPI has good NoSQL DBs support. And I wanna to use Django and FAST API in one project. If you have solution of my problem, please drop me a link to solution. Maybe will be better if I'll use them separately (1 django server and 1 Fast API server) and frontend will request data from 2 different servers? -
Error in Serving media images with Django
Problem - When trying to fetch an image leads to 404 error URL Declarations - from django.urls import include, path from rest_framework import routers from django.conf.urls.static import static from django.conf import settings from my_awesome_api.views import PersonViewSet, SpeciesViewSet router = routers.DefaultRouter() router.register(r'people', PersonViewSet) router.register(r'species', SpeciesViewSet) urlpatterns = [ path('', include(router.urls)), ] urlpatterns+= static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) print('avail url patterns') print(urlpatterns) VIEW DECLARATION - from django.shortcuts import render from rest_framework import viewsets from rest_framework.parsers import MultiPartParser, FormParser from rest_framework import permissions from my_awesome_api.serializers import PersonSerializer, SpeciesSerializer from my_awesome_api.models import Person, Species class PersonViewSet(viewsets.ModelViewSet): queryset = Person.objects.all() serializer_class = PersonSerializer parser_classes = (MultiPartParser, FormParser) #permission_classes = [permissions.IsAuthenticatedOrReadOnly] def perform_create(self, serializer): serializer.save() class SpeciesViewSet(viewsets.ModelViewSet): queryset = Species.objects.all() serializer_class = SpeciesSerializer parser_classes = (MultiPartParser, FormParser) #permission_classes = [permissions.IsAuthenticatedOrReadOnly] def perform_create(self, serializer): serializer.save() MODEL DECLARATION - from django.db import models # Create your models here. class Species(models.Model): name = models.CharField(max_length=100) classification = models.CharField(max_length=100) language = models.CharField(max_length=100) image_url = models.ImageField(blank=True, null=True) class Person(models.Model): name = models.CharField(max_length=100) birth_year = models.CharField(max_length=10) eye_color = models.CharField(max_length=10) species = models.ForeignKey(Species, on_delete=models.DO_NOTHING) image_url = models.ImageField(blank=True, null=True) SETTING DECLARATION MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'media') print(MEDIA_ROOT) print('value of media root') # URL used to access the media MEDIA_URL = 'media/' In an effort to troubleshoot the problem, I … -
How to implement datatable server side from this code using django
Currently I have this code that shows me the normal data table but if I have millions of records it becomes very slow, I understand that serverside of datatable can be used but I don't know how I can implement it list.html <table class="table table-striped table-hover responsive" style="width:100%" id="buyer"> <thead> <th>#id</th> <th>Fecha</th> <th>Cod Cliente</th> <th>Cliente</th> <th>Dirección</th> <th>Comentario</th> <th>Tipo Retiro</th> <th>Total</th> <th>Guias a Generar</th> </thead> <tbody> {% for item in ResulOrdenes %} <tr> <td>{{item.DOCNUM}}</td> <td>{{item.DOC_DATE|date:"Y-m-d"}}</td> <td>{{ item.CARDCODE }}</td> <td>{{ item.CARDNAME }}</td> <td>{{ item.ADDRESS }}</td> <td>{{ item.COMMENTS }}</td> <td>{{ item.URETIRO }}</td> <td>{{ item.DOCTOTAL }}</td> <td>{{ item.NGUIAS }}</td> </tr> {% endfor %} </tbody> </table> </div> {% endblock %} {% block content_wrapper %} <p></p> {% endblock content_wrapper %} {% block js_page %} <script> $(document).ready(function() { $('.table').DataTable({ dom: 'Bfrtip', }); </script> {% endblock %} view.py def Listado_guia(request): template_name='app_listguia/lista.html' conn = dbapi.connect(..) cursorSol2 = conn.cursor() sql_command = 'select a."DocNum" as "DOCNUM", a."DocDate" as "DOC_DATE", a."CardCode" as "CARDCODE", a."CardName" as "CARDNAME", a."DocTotal" as "DOCTOTAL", CEILING(a."DocTotal"/20000) as "NGUIAS", a."DocStatus" as "DOCSTATUS", a."Address" as "ADDRESS", a."Address2" as "ADDRESS2", a."Comments" as "COMMENTS", a."U_Retiro_mercaderia" as "URETIRO" ' sql_command = sql_command + 'from "'+ connections.databases[ConfigBaseHana]["NAME"] +'"."ODLN" as a ' cursorSol2.execute(sql_command) RES_ORDENES = cursorSol2.fetchall() cursorSol2.close() conn.close() dnow = today.strftime("%Y-%m-%d") contexto = { "ResulOrdenes":RES_ORDENES, … -
How to append a string to url in django template tag?
I have two sections in my demo site. blog and tweets. In header of parent HTML file I have Blog, Tweets and "New +". To create object for one of these two. I want for "new +" link to go http://127.0.0.1:8000/blog/new or http://127.0.0.1:8000/tweets/new How to append new to both of these link when I'm in either of these two links <a href="{% url 'tweets' %}">Tweets</a> <a href="{% url 'blog' %}">blog</a> Both of these links work but I want blog/new or tweets/new when I'm in one of these links without hardcoding. -
Optgroup/Option dropdown Django
I am working on a form which has a select dropdown that requires an optgroup and select options… Optgroups are Regions (Asia, Europe etc) and options are countries belonging to the countries… I have developed a Form for this and applied choicefield and has written the logic inside the form itself… and then applied the HTML using FormHelper Layout so that I can just pass {% crispy form %} in the template… For some reason I cannot figure out, the data in the select option does not appear… I’d appreciate if you could help me debug the problem… Please note, there is no error message, just that when i go to webpage, the data in the dropdown isnt there… Models.py class CountryRegion(models.Model): id = models.AutoField(primary_key=True, editable=False) country_name = models.CharField(max_length=50, unique=True, verbose_name='Segment') region_name = models.CharField(max_length=50, verbose_name='Industry') class Meta: verbose_name_plural = 'RegionCountry' def __str__(self): return self.country_name + '-' + self.region_name Forms.py from django import forms from crispy_forms.helper import FormHelper from crispy_forms.layout import Submit, Layout, Row, Column, HTML from crispy_forms.bootstrap import FormActions from django.contrib.auth.models import User from django.forms import ModelForm from .models import Portfolio, Project, SegmentIndustry, CountryRegion class ProjectForm(forms.ModelForm): fk_project_location = forms.ChoiceField(choices=[]) def __init__(self, *args, **kwargs): super(ProjectForm, self).__init__(*args, **kwargs) region_list = CountryRegion.objects.values_list( "region_name", … -
ListView get_context_data
question about Django. Would like to ask you guys if it's possible to use get_context_data in ListView? I am interested in using the following template tags in my ListView: {% if liked %} <i class="fa-solid fa-thumbs-up"></i> {% else %} <i class="fa-regular fa-thumbs-up"></i> {% endif %} This works in my DetailView but I can't figure out how to implement it in ListView maybe you guys can help me? This is my views.py class PostList(generic.ListView): model = Post queryset = Post.objects.order_by('-created_on') template_name = 'blog/blog.html' class PostDetail(generic.DetailView): model = Post template_name = 'blog/post_detail.html' def get_context_data(self, **kwargs): context = super(PostDetail, self).get_context_data(**kwargs) context['comments'] = self.object.comments.order_by('-created_on') context['liked'] = self.object.likes.filter(id=self.request.user.id).exists() return context I'm testing get_context_data i ListView but can't get it to work. -
How to pass text argument to custom widget in django form?
I'd like to display a dynamic text value in a custom widget. It will more or less be a bootstrap input group with some dynamic text in a input-group-append element. I'm having difficulty understanding how I can pass this through to the template, as when I define the field in the Form class, I can't seem to reference arguments from the Form constructor. I'm inexperienced with both python and django so its very likely I'm missing some foundational python knowledge that's causing my confusion. If I do this, the widget renders partially ok (There is an automatic label "Site prefix" rendered that I don't want but that seems like a different problem) class SiteNameForm(forms.Form): site_prefix = forms.CharField(widget=SiteNameInputWidget(prefix_for='T E S T'), label=None) And create the form like so form = SiteNameForm() However, I need to pass in a dynamic value, so I tried class SiteNameForm(forms.Form): def __init__(self, prefix_for=None, *args, **kwargs): self.prefix_for = prefix_for self.site_prefix = forms.CharField(widget=SiteNameInputWidget(prefix_for=self.prefix_for)) super().__init__(self, args, kwargs) While creating the form form = SiteNameForm(prefix_for='TEST') But when I do that, nothing is rendered at all, not even the automatic label that I didn't want. The template specified as template_name <div class="row"> <div class="input-group mb-3"> <div class="input-group-prepend"> <span class="input-group-text">https://</span> </div> <input … -
How can I test render methods for django template Node?
I have written a django template Node for templatetag. How can I test render method (render method only) for Node? Here is my code sample: class SVGNode(Node): child_nodelists = () def __init__(self, svg_name, args: list, kwargs: dict) -> None: ... def __repr__(self) -> str: return ... def render(self, context: Context) -> str: ... return svg And I want to test it using pytest(preferably).