Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
on multiplying weight into price i'm getting the total price as a multiplication of string but I want integer as total price
veiws.py: def sell(request): global Price Metal = "Metal" Steel = "Steel" copper = "copper" plastic = "plastic" Aluminium = "Aluminium" if request.method == "POST": user = request.user Scrap = request.POST.get('Scrap', '') Weight = request.POST.get('Weight', '') Address1 = request.POST.get('Address1', '') Address2 = request.POST.get('Address2', '') locality = request.POST.get('locality', '') if Scrap.__eq__(Metal): Price = 12 elif Scrap.__eq__(Steel): Price = 10 elif Scrap.__eq__(copper): Price = 6 elif Scrap.__eq__(plastic): Price = 2 elif Scrap.__eq__(Aluminium): Price = 30 x = Price price = float(x) Total_price = price * Weight order = Orders(Scrap=Scrap, Total_Price=Total_price, Weight=Weight, Address1=Address1, Address2=Address2, locality=locality, user=user) order.save() thank = True id = order.order_id return render(request, 'Main/sell.html', {'thank': thank, 'id': id}) return render(request, 'Main/sell.html',) models.py selling form I chose metal whose price is 12 and weight I have taken 12 kg so as the total price I should get 144 But i am getting this -
How can I do username in reviews on django?
I'm doing reviews on django, but I want the user to not be able to enter any name. I want the username in the reviews to match the username of his profile models.py class Reviews(models.Model): name = models.CharField('Имя', max_length=100) text = models.TextField('Отзыв', max_length=3400) parent = models.ForeignKey('self', verbose_name='Родитель', on_delete=models.SET_NULL, null=True, blank=True) book = models.ForeignKey(BookModel, verbose_name='книга', on_delete=models.CASCADE) name_user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) views.py class MoreInfoView(View): """ """ def get(self, request, id): book_info = BookModel.objects.filter(id=id).first() stuff = get_object_or_404(BookModel, id=self.kwargs['id']) total_likes = stuff.total_likes() return render(request, 'bookapp/more_info.html', context={ 'id': id, 'book_info': book_info, 'book': BookModel.objects.all(), 'total_likes': total_likes, }) class AddReview(View): """Add Review""" def post(self, request, pk): form = ReviewForm(request.POST) book = BookModel.objects.get(id=pk) if form.is_valid(): form = form.save(commit=False) form.book = book form.save() return HttpResponseRedirect(reverse('more_info', args=[pk])) forms class ReviewForm(forms.ModelForm): class Meta: model = Reviews fields = ("name", "text", 'name_user') -
Why is the colour not saved if the localStorage is correct?
I'm making it save the colour in localStorage to see a red heart if liked and no colour if disliked after refreshing the web page. But I don't understand why it is not shown. I have debugged and the localSotage values are correct. Index.js const color = ["#000000", "#FF0000"]; let colorIndex = parseInt(localStorage.getItem("colorIndex")) || 0; console.log("Initial: " + colorIndex); function like(elem) { const postId = elem.attributes["data-id"].value const csrftoken = getCookie('csrftoken'); fetch(`like/${postId}`, { method: 'POST', headers: { 'X-CSRFToken': csrftoken }, mode: 'same-origin' }).then(res => res.json()) .then(data => { document.getElementById(postId).innerText = data.numLikes console.log(data.liked + ", color: " + color[data.numLikes - 1]); if (data.liked == true) { colorIndex = data.isLiked; document.getElementById(`icon-${postId}`).setAttribute("fill", color[colorIndex]); console.log("liked == true " + colorIndex); } else if (data.liked == false) { colorIndex = data.isLiked; document.getElementById(`icon-${postId}`).setAttribute("fill", color[colorIndex]); console.log("liked == false " + colorIndex); } localStorage.setItem("colorIndex", colorIndex); }) } views.py if request.method == "POST": postId = Post.objects.get(id = id) # Almacena los id de cada post if not postId.likes.filter(id = request.user.id).exists(): # Si no existe un like por el usuario newStatus = True isLiked = 1 postId.likes.add(request.user) # Añadelo postId.save() else: newStatus = False isLiked = 0 postId.likes.remove(request.user) # Si no lo quitas postId.save() return JsonResponse({"liked": newStatus, "isLiked": isLiked, "id": id, … -
HTMX multiple event on one element - each event executing different request
Summary, How do I attach a click and a dblclick on same element in HTMX and also have each of the event executing different request (views). .I am new to HTMX using django and i have this list <li class="list-group-item" hx-get="{% url 'quality:list' competence.pk %}" hx-target="#quality-list" hx-trigger="click" > it works fine using the click event. I however also want it to execute another view (quality:update) when a dblclick is fired on it. i.e. on same element (li) click should implement details function and dblclick should implement update function -
'social' is not a registered namespace
Im trying to implement google authentication but I got the following error: django.urls.exceptions.NoReverseMatch: 'social' is not a registered namespace i have like this in my login.html: <a href="{% url 'social:begin' 'google-oauth2' %}"> Sign in with Google</a> I also added this in my setting.py SOCIAL_AUTH_URL_NAMESPACE = 'social' url.py urlpatterns = [ path('admin/', admin.site.urls), path('register/', user_views.register, name='register'), path('profile/', user_views.profile, name='profile'), path('login/', auth_views.LoginView.as_view(template_name='users/login.html'), name='login'), path('login/', include('allauth.urls')), path('logout/', auth_views.LogoutView.as_view(template_name='users/logout.html'), name='logout'), path('', include('blog.urls')), ] Does anyone know how to solve this? -
How to encrypt connection with Django server?
I have a Django REST framework API and I have a problem - connection with the server is not encrypted. Is there a method to encrypt the server and the connection to it? I use Django for backend and React.js for frontend. -
Jquery validation for multi-step form
I am new to jQuery and I have no idea how to implement some jQuery validation on a jQuery form I downloaded. The following code is working but is wrong as it has inside . I'm using Python Django and injecting fields with forms.py. <section class="horizontal-wizard"> <div class="bs-stepper horizontal-wizard-example"> <div class="bs-stepper-header" role="tablist"> <div class="step" data-target="#account-details" role="tab" id="account-details-trigger"> <button type="button" class="step-trigger"> <span class="bs-stepper-box">1</span> <span class="bs-stepper-label"> <span class="bs-stepper-title">Account Details</span> <span class="bs-stepper-subtitle">Setup Account Details</span> </span> </button> </div> <div class="line"> <i data-feather="chevron-right" class="font-medium-2"></i> </div> <div class="step" data-target="#personal-info" role="tab" id="personal-info-trigger"> <button type="button" class="step-trigger"> <span class="bs-stepper-box">2</span> <span class="bs-stepper-label"> <span class="bs-stepper-title">Personal Info</span> <span class="bs-stepper-subtitle">Add Personal Info</span> </span> </button> </div> <div class="line"> <i data-feather="chevron-right" class="font-medium-2"></i> </div> <div class="step" data-target="#address-step" role="tab" id="address-step-trigger"> <button type="button" class="step-trigger"> <span class="bs-stepper-box">3</span> <span class="bs-stepper-label"> <span class="bs-stepper-title">Address</span> <span class="bs-stepper-subtitle">Add Address</span> </span> </button> </div> <div class="line"> <i data-feather="chevron-right" class="font-medium-2"></i> </div> <div class="step" data-target="#social-links" role="tab" id="social-links-trigger"> <button type="button" class="step-trigger"> <span class="bs-stepper-box">4</span> <span class="bs-stepper-label"> <span class="bs-stepper-title">Social Links</span> <span class="bs-stepper-subtitle">Add Social Links</span> </span> </button> </div> </div> <div class="bs-stepper-content"> <div id="account-details" class="content" role="tabpanel" aria-labelledby="account-details-trigger"> <div class="content-header"> <h5 class="mb-0">Account Details</h5> <small class="text-muted">Enter Your Account Details.</small> </div> <form name="form" method="POST" enctype="multipart/form-data"> {% csrf_token %} <form> <div class="row"> <div class="mb-1 col-md-6"> <label class="form-label" for="{{userform.username.id_for_label}}">{{userform.username.label}}</label> <label class="error">{{userform.username.errors}}</label> {{userform.username}} </div> <div class="mb-1 col-md-6"> <label class="form-label" … -
How to send data from HTML form input type number to a variable in app views.py Django
Here is input type number in template file <form action="" method="get"> <input class="form-control m-3 w-50 mx-auto" type="text" name="question" id="question" placeholder="Enter Something..."> <input type="number" id="typeNumber" class="form-control m-3 w-50 mx-auto" /> <input class="btn btn-primary btn-lg my-3" type="submit" value="Check Now"> </form> I want to get the number that is selected by the user. I want to keep the number in a variable in views.py file. How can I get this? Thanks -
How can I make POST request with nested form data on POSTMAN?
I am testing a POST request in which I need the body structure to be something like this. { "new_status":"", "insertions":[ {"seq":"1", "type":"heading", "value":"My sub heading 1" }, {"seq":"2", "type":"datetime", "value":"1-12-2022" }, {"seq":"3", "type":"pdf", "value":"A PDF FILE attached here " } ] } Django backend In the server side I am getting the data from the POST like this 'insertions[0]pdf': [<InMemoryUploadedFile: IN-APR-01.pdf (application/pdf)>]}> Internal Server Error: /api/content In the last object, I want to insert A PDF FILE This data is reaching the server but not in a way that I need. How can I send a nested Array of Objects via postman ? -
Why can't Open AI read from my site and yet it has no issues crawling other sites? It doesn't seem to know that my site exists
I made a site where people can get to upload documents and Open AI can view and summarise them for them, or perform other operations on them. However, for some reason, in the Playground, Open AI can't read from my site but can read from other sites with no problem. I thought it was an issue with my server so I even hosted the site on two different ones, and still, it won't work. The site is at heroku and pythonanywhere I used simple 'bot friendly code' if there is such a thing... but Open AI still can't see the document. Is there a way that I can mitigate this problem? Maybe it has something to do with the servers? Or DNS? I really don't know. -
Django: how to connect customizable url to GET method
I want to implement a search method that takes as filters properties selected by user from front-end side. The URL I want to create would be something like: urls.py: urlpatterns = [ path('', views.get_data), path(r'^find/<property>/<filter>/<value>', views.filter_view) ] Where is the value (1-9) selected from: <div class="dropdown-wrapper" style="padding-left: 0px"> <select class="dropdown" id="select-properties-dropdown"> <option class="property" value="0">Select property</option> <option class="property" value="1">GID</option> <option class="property" value="2">Type</option> <option class="property" value="3">Province</option> <option class="property" value="4">Street</option> <option class="property" value="5">House number</option> <option class="property" value="6">Postcode</option> <option class="property" value="7">City</option> <option class="property" value="8">Municipality</option> </select> </div> is the value from: <div class="dropdown-wrapper" > <select class="dropdown"> <option class="property" value="0">Contains</option> <option class="property" value="1">Equal to</option> <option class="property" value="2">Ends with</option> <option class="property" value="3">Starts with</option> </select> </div> and is the taken from the searchbar: <div class="dropdown-wrapper"> <form action="find" method="GET"> <input class="input searchbar" type="text" aria-autocomplete="list" aria-expanded="false" id="searchBar" style="height: 28.5px" > <button type="submit"><i class="fa fa-search"></i> </button> </form> </div> -
Django - How to save an image from a blob URL
I have a blob URL stored in a Django model field and I want to convert it to an image and save it to an ImageField. Here is my code in models.py : class Message(models.Model): author = models.ForeignKey(Account, on_delete=models.CASCADE) room = models.CharField(max_length = 255) content = models.TextField() date_added = models.DateTimeField(null=True, blank=True) image = models.ImageField(null=True, blank=True, upload_to='message_images') image_url = models.URLField(max_length=255, unique=True) class Meta: ordering = ('date_added', ) def save(self, *args, **kwargs): super().save(*args, **kwargs) #Trying to save the image here img = Image.open(self.image_url) img.save(self.image.path) Question: How can I convert the blob to an image and save it? -
Running a Django application from a cloned repository that has environment variables
I'm trying to run a Django application from a cloned repository and I noticed that it has environment variables stored in the settings.py file(namely: the SECRET_KEY and DEBUG). When running the application, it gives me the following error: django.core.exceptions.ImproperlyConfigured: Set the SECRET_KEY environment variable I understand that Django cannot run without it but I have the following doubts regarding this problem. Should I provide my own SECRET_KEY and declare it inside a .env file. Also, is it necessary to have the same SECRET_KEY as the original project file did? -
Nginx not serving static files /Django
When I deploy my project to server using Nginx and Gunicorn static files are not loading. This is how my website looks after deploying nginx.service is as follows user nginx; worker_processes auto; error_log /var/log/nginx/error.log notice; pid /var/run/nginx.pid; events { worker_connections 1024; } http { include /etc/nginx/mime.types; default_type application/octet-stream; log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"'; access_log /var/log/nginx/access.log main; sendfile on; #tcp_nopush on; keepalive_timeout 65; #gzip on; include /etc/nginx/conf.d/*.conf; server { listen 8081; server_name 0.0.0.0; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root home/zp_dashboard_testing_python/zp_main/staticfiles; } location / { proxy_set_header Host $http_host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_pass http://unix:/run/gunicorn.sock; } } } settings.py BOOTSTRAP4 = { 'include_jquery': True, } STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static") ] STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') I have run collectstatic command and it gives some warnings file already found at destination path, but its just a warning and not an error. nginx error logs are as follows 2022/05/01 19:27:49 [error] 77154#77154: *5 open() "/etc/nginx/home/zp_dashboard_testing_python/zp_main/staticfiles/static/assets/libs/datatables.net-buttons/js/buttons.html5.min.js" failed (2: No such file or directory), client: 10.81.234.6, server: 0.0.0.0, request: "GET /static/assets/libs/datatables.net-buttons/js/buttons.html5.min.js HTTP/1.1", host: "10.10.89.25:8081", referrer: "http://10.10.89.25:8081/dashboard/" 2022/05/01 19:27:49 [error] 77154#77154: *7 open() "/etc/nginx/home/zp_dashboard_testing_python/zp_main/staticfiles/static/assets/libs/datatables.net-buttons/js/buttons.print.min.js" … -
Django multiple relations in one model
I have been trying to create a model that could represent the form as it is, tried creating an EntryForm model which is linked to EntryFormTable where then each column in the table is a model class all linked to the table, but then this proved to be a long way and one that doesn't even work, maybe there's a short or even a working method to represent this in django models, -
AttributeError: module 'typing' has no attribute '_ClassVar'
I've completed the deployment of the Django project on Azure Web App. However, if I attempt to launch my program, this error is recorded in the log. I have absolutely no idea what is going on. Even I am confused as to why the dataclasses are being constructed. Anyone who can assist me would be much appreciated; I need assistance with this difficulty. 2022-05-01T13:49:50.189019473Z 2022-05-01T13:49:50.189048674Z _____ 2022-05-01T13:49:50.189060474Z / _ \ __________ _________ ____ 2022-05-01T13:49:50.189064774Z / /_\ \___ / | \_ __ \_/ __ \ 2022-05-01T13:49:50.189068474Z / | \/ /| | /| | \/\ ___/ 2022-05-01T13:49:50.189072174Z \____|__ /_____ \____/ |__| \___ > 2022-05-01T13:49:50.189075874Z \/ \/ \/ 2022-05-01T13:49:50.189079574Z 2022-05-01T13:49:50.189083074Z A P P S E R V I C E O N L I N U X 2022-05-01T13:49:50.189087974Z 2022-05-01T13:49:50.189091474Z Documentation: http://aka.ms/webapp-linux 2022-05-01T13:49:50.189094974Z Python 3.9.7 2022-05-01T13:49:50.189098374Z Note: Any data outside '/home' is not persisted 2022-05-01T13:49:50.465258799Z Starting OpenBSD Secure Shell server: sshd. 2022-05-01T13:49:50.566940080Z App Command Line not configured, will attempt auto-detect 2022-05-01T13:49:50.574021984Z Launching oryx with: create-script -appPath /home/site/wwwroot -output /opt/startup/startup.sh -virtualEnvName antenv -defaultApp /opt/defaultsite 2022-05-01T13:49:50.606042350Z Found build manifest file at '/home/site/wwwroot/oryx-manifest.toml'. Deserializing it... 2022-05-01T13:49:50.607452471Z Build Operation ID: |Y2+7faeVpcs=.7771bea2_ 2022-05-01T13:49:50.608042879Z Oryx Version: 0.2.20211207.1, Commit: 46633df49cc8fbe9718772a3c894df221273b2af, ReleaseTagName: 20211207.1 2022-05-01T13:49:50.608069580Z Output is compressed. Extracting it... 2022-05-01T13:49:50.624718722Z Extracting '/home/site/wwwroot/output.tar.gz' … -
django admin popups are broken when using 'collect static', what might be the problem?
When I try to press + on a many-to-many or foreign-key or any field like that, it usually gives me a popup window. Now it's just redirecting me to URL.../model/add/?_to_field=id&_popup=1 which complicates everything. I read and tried these posts, but none of them helped: Django admin add related object doesn't open popup window? https://github.com/sehmaschine/django-grappelli/issues/600 Django admin popup links are broken After experimenting with Django, I found out that only happens when you use python manage.py collectstatic When you delete everything from the static folder, it gets fixed. What might be the problem? I'm not using any special thing, I made a fresh boilerplate Django application, added 2 models, and ran collect static, and it still happened. Django version: 4.0.3 Python version: 3.10.2 Pip version: 22.0.4 -
How to query data with datetime month paramenter?
I have filter function to query data based on month. I use Calendar. Here is my code : def ListAll(request): list_month = list(calendar.month_name)[1:] list_year = Year.objects.all() objects = Rental.objects.filter(is_terminate = True).order_by('-created') year_query = request.GET.get("year") month_query = request.GET.get("month") if month_query : month_number = list(calendar.month_name).index(month_query) month_number = int(month_number) objects = Rental.objects.filter(is_terminate=True, created__month=month_number, created__year=year_query).order_by('-created') context = { 'objects':objects, 'list_month': list_month, 'list_year': list_year } return render(request, 'report_rental/all.html', context) In my model, field created: models.DateTimeField(auto_now_add=True) My problem is, i got Empty data with query using month with this objects = Rental.objects.filter(is_terminate=True, created__month=month_number, created__year=year_query).order_by('-created') Does anyone can help me? Thank you -
How to using loop to show all images in my web page- HTML, django, Boostrap?
My views: def home (request): user = request.user Movies_obj = models.Movies.objects.all() return render(request, 'home.html', {'user': user, 'movies1': Movies_obj[:4], 'movies2': Movies_obj[4:8], 'movies3': Movies_obj[8:12]}) My HTML: <div class="carousel-inner"> <div class="carousel-item active"> <div class="row"> {% for mv1 in movies1 %} <div class="col"> <img class="img-thumbnail" src="{{mv1.image.url}}" alt="First Slide" width="100%"> </div> {% endfor %} </div> </div> <div class="carousel-item"> <div class="row"> {% for mv2 in movies2 %} <div class="col"> <img class="img-thumbnail" src="{{mv2.image.url}}" alt="First Slide" width="100%"> </div> {% endfor %} </div> </div> <div class="carousel-item"> <div class="row"> {% for mv3 in movies3 %} <div class="col"> <img class="img-thumbnail" src="{{mv3.image.url}}" alt="First Slide" width="100%"> </div> {% endfor %} </div> </div> Previous Next -
Chart js and django for long data
On my django app , i need to create a line visualization using chart js exemple of one value : 0;-0.0110227457430789;-0.0117428254241928;-0.0125132024365239;-0.0120122425942302;-0.0121398995885254;-0.0127606573714123;-0.0123882233559148;-0.0126683380476791;-0.0125534489771807;-0.0114614833910938;-0.0139670311717919;-0.0117059991385652;-0.0127469146854689 is it possible to use chart js with this size of data ? <canvas id="myChart" width="400" height="400"></canvas> <script> const ctx = document.getElementById('myChart').getContext('2d'); const myChart = new Chart(ctx, { type: 'bar', data: { labels: [{% for s in data%} {{s.sampleID}} {%endfor%} ], datasets: [{ label: '# of Votes', data: [{% for s in data%} {{s.absorbance}} {%endfor%} ], backgroundColor: [ 'rgba(255, 99, 132, 0.2)', 'rgba(54, 162, 235, 0.2)', 'rgba(255, 206, 86, 0.2)', 'rgba(75, 192, 192, 0.2)', 'rgba(153, 102, 255, 0.2)', 'rgba(255, 159, 64, 0.2)' ], borderColor: [ 'rgba(255, 99, 132, 1)', 'rgba(54, 162, 235, 1)', 'rgba(255, 206, 86, 1)', 'rgba(75, 192, 192, 1)', 'rgba(153, 102, 255, 1)', 'rgba(255, 159, 64, 1)' ], borderWidth: 1 }] }, options: { scales: { y: { beginAtZero: true } } } }); </script> -
Customize Form with Django FORM API
I am currently creating an register/login form with the Django framework, since I am new to this framework, I don't know much about the FORM API. I am not using the FORM API, since I don't know if I can customize it. Is there any way to use my styling with the FORM API? As the state of now, I am just creating my own one, without using the API, but since the FORM API is more secure and much faster to set up for user creation, I would like to use it. Can I just implement the API into my html code, without putting out my classes and styling? Here is my HTML form: {% if messages %} <ul class="messages"> {% for message in messages %} <li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li> {% endfor %} </ul> {% endif %} <div class="limiter"> <div class="container-login100" style="background:black;"> <div class="wrap-login100"> <form class="login100-form validate-form" method='POST' action="{% url 'users:register' %}" > {% csrf_token %} <span class="login100-form-logo"> <i class="zmdi zmdi-landscape"></i> </span> <span class="login100-form-title p-b-34 p-t-27"> Register </span> <div class="wrap-input100 validate-input" data-validate = "Enter username"> <input class="input100" type="text" name="username" placeholder="Username" required> <span class="focus-input100" data-placeholder="&#xf207;"></span> </div> <div class="wrap-input100 validate-input" data-validate="Enter password"> <input class="input100" … -
Database relationship between a match and its players
I'm trying to design a database that would save matches and players in a 3v3 game. So far my models look like this : class Player(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True) player_tag = models.CharField(max_length=9, unique=True) player_name = models.CharField(max_length=50) trophy_count = models.IntegerField(default=0) club = models.ForeignKey('Club', on_delete=models.SET_NULL, null=True) total_club_war_trophy_count = models.IntegerField(default=0) class Club(models.Model): club_name = models.CharField(max_length=50) club_tag = models.CharField(max_length=9, unique=True) class Match(models.Model): # Matches are 3v3 player_1 = models.ForeignKey(Player, on_delete=models.CASCADE) player_2 = models.ForeignKey(Player, on_delete=models.CASCADE) player_3 = models.ForeignKey(Player, on_delete=models.CASCADE) player_4 = models.ForeignKey(Player, on_delete=models.CASCADE) player_5 = models.ForeignKey(Player, on_delete=models.CASCADE) player_6 = models.ForeignKey(Player, on_delete=models.CASCADE) # Brawlball, Gem grab, Knockout ... mode = models.CharField(max_length=20) # Power match or normal match battle_type = models.CharField(max_length=20) trophies_won = models.IntegerField(default=0) date = models.DateTimeField(auto_now_add=True) However the repetition of "player_<int>" is itching me, I don't think this is the proper way to do it. What if the number of player changes at some point, or how to I find if a player participated in a match ? I think it's a clunky approach at best. How could I approach this better ? I was thinking about maybe a list of players, but I don't know how to characterize this kind of relationship. -
Django on Elastic Beanstalk
I zipped my Django project and dropped it in the AWS Elastic Beanstalk service. My plan is to leverage IAM to deliver fine grained access to the SQL database populated via my Django app and otherwise from client device data (via MS ActiveDirectory, ) and patient files downloaded from obsolete devices. Am curious whether experts recommend populating my templates with AWS CLI code (to implement the IAM infrastructure programmatically) before I move the zipped files to EB or whether I can make adjustments to the Django templates sitting in EB already (perhaps from cloud9 or thru updates). First problem to address tho: my EB app status is "severe." Still troubleshooting the "severe" status issue. -
{% url ... %} templatetag in Django included template not seeing variable
I'm experiencing strange behaviour in an included template which I can't figure out. parent_template.html {% for item in items %} Parent: {{ item.pk }} {% include 'child_template.html' %} {% endfor %} child_template.html Child: {{ item.pk }} URL: {% url 'some_named_url' item.pk %} I get a reverse error: Reverse for '/test/url/<int:pk>/' with arguments '('',)' not found. 1 pattern(s) tried: ['test/url/(?P<pk>[0-9]+)/\\Z'] If however I remove the {% url ... %} template tag, it renders correctly and shows: Parent: 1 Child: 1 So it's clear that item is in the context, but for some reason it isn't being passed to the templatetag. I have also tried variations like: {% for item in items %} {% with new_item=item %} {% include 'child_template.html' %} {% endwith %} {% endfor %} Any ideas? I am using Django 3.2.12 -
Translate WKT geometry from database into GeoJSON using Django
I have a database with schools that have as attributes geometry in this format: 01040000000100000001010000000CC47A46B78BF64038FB9CC22D731A41 I was wondering how can I translate this geometry into latitude and longitude using django. views.py: from django.http import JsonResponse from django.shortcuts import render from rest_framework.decorators import api_view from base.models import RSchools as School from definitions import ROOT_DIR from .serializers import SchoolSerializer @api_view(['GET']) def get_data(request): schools = School.objects.all() for school in schools: #PREPROCESS EACH SCHOOL GEOMETRY HERE INTO LATITUDE AND LONGITUDE pass return render(request, f'{ROOT_DIR}/templates/tst/index.html', {'schools': schools}) models.py: from django.db import models # Create your models here. class RSchools(models.Model): gid = models.AutoField(primary_key=True) schooltype = models.CharField(max_length=254, blank=True, null=True) provincie = models.CharField(max_length=254, blank=True, null=True) straatnaam = models.CharField(max_length=254, blank=True, null=True) huisnummer = models.CharField(max_length=254, blank=True, null=True) postcode = models.CharField(max_length=254, blank=True, null=True) plaatsnaam = models.CharField(max_length=254, blank=True, null=True) gemeentena = models.CharField(max_length=254, blank=True, null=True) geom = models.TextField(blank=True, null=True) # This field type is a guess. class Meta: # managed = False db_table = 'r_schools'