Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
jQuery String Matching Django Generated String
I have a script that highlights certain blocks of text on a page generated by Django. The script works fine until the block of text contains an apostrophe. It won't match in that case. I've tried various combinations of filters, escaping, etc. but can't seem to get it working. Below is my code. jQuery in template: <script> $(document).ready(function(){ // Displays highlights if any exist {% for highlight in agenda.highlights.all %} $( "div.card-body div.mb-3:contains('{{ agenda.agenda_text|hl_slice:highlight }}')" ).css( "background-color", "#FFFF00" ).attr("id", "{{ highlight.id }}"); {% endfor %} }); </script> Django "hl_slice" custom filter @register.filter @stringfilter def hl_slice(agenda_text, hl): """ Returns the highlighted portion of the agenda text. """ try: hl_text = strip_tags(agenda_text[hl.start:hl.end]) return hl_text except (ValueError, TypeError): return hl # Fail silently. Text blocks in template (generates HTML divs containing text) {{ agenda.agenda_text|safe }} Here is an example of text that breaks the match: "K. 20-378 Notification of City Manager's and Assistant City Manager's execution of Professional Consultant Agreements and Amendments to an Agreement, as well as Public Construction Contracts not subject to the Competitive Bid Act, with a Contract values of less than $25,000" If I take out the apostrophes, the text will match, so I know it has something to … -
Center bootstrap toggle navbar
**Hi, I have struggled all day to make my navbar center on the page without any luck. I have used bootstrap to create the navbar. I would be extremely happy if someone could help me out.** URL <!DOCTYPE html> <html lang="en"> <head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <!-- Required meta tags --> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> </head> <body> <nav class="navbar navbar-expand-lg navbar-light bg-info d-flex justify-content-center"> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarTogglerDemo03" aria-controls="navbarTogglerDemo03" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse h3" id="navbarTogglerDemo03"> <ul class="navbar-nav mr-auto mt-2 mt-lg-0"> <li class="nav-item"> <a class="nav-link" href="#">Home</a> </li> <li class="nav-item"> <a class="nav-link" href="#">Link</a> </li> <li class="nav-item"> <a class="nav-link" href="#">Link</a> </li> <li class="nav-item"> <a class="nav-link" href="#">Link</a> </li> </ul> </div> </nav> <div class="jumbotron jumbotron-fluid bg-info text-white text-center""> <div class="container"> <h1 class="display-4">c.magelssen</h1> <p class="lead">A resource on psychology, teaching, skiing and coding.</p> </div> </div> </div> -
Pass data from template to django's views.py
Right now i'm working on the pagination of the data table at my django's project. And i'm trying to let the user put how many registers are displayed per page, but i'm having troubles passing the number at the selector that i'm using to views.py (where the pagination is), my question is: How to pass the selected number to views.py so it updates the registers? this is my code: Template's Selector: <form action="" method="POST"> <select class="selector" id="estado" name="estado" onchange="post()" style="border-color: #C9C9C9; color:black; height: 25px; width:100px; position:absolute; margin-top:-32px; margin-left:230px;"> <option selected style="color:black;">5</option> <option style="color:black;">10</option> <option style="color:black;">25</option> <option style="color:black;">50</option> <option style="color:black;">100</option> </select> </form> Views.py: if request.method == 'POST': inicial = { 'paginas' : 5, } num = paginaForm(initial = inicial).fields['paginas'] else: num = 5 riesgos = Riesgos.objects.all() #Paginación paginator = Paginator(riesgos, num) page = request.GET.get('page') try: items = paginator.page(page) except PageNotAnInteger: items = paginator.page(1) except EmptyPage: paginator.page(paginator.num_pages) index = items.number - 1 max_index = len(paginator.page_range) start_index = index - 5 if index >= 5 else 0 end_index = index + 5 if index <= max_index - 5 else max_index page_range = paginator.page_range[start_index:end_index] context = {'riesgos':riesgos, 'page_range':page_range, 'items':items} return render(request,'restapi/listar_riesgo.html', context) Models.py class Paginas(models.Model): paginas = models.IntegerField(primary_key= True) Forms.py: class paginaForm(forms.ModelForm): class Meta: … -
Static files path loading inconsistency with bootstrap files in Django
{% load static %} <link rel="stylesheet" href="{% static "css/bootstrap.min.css" %}"/> <link rel="stylesheet" href="{% static "pages/css/main.css" %}"/> <!-- body of page --> <script src="{% static "pages/js/jquery-3.4.1.min.js" %}"></script> <script src="{% static "js/bootstrap.bundle.min.js" %}"></script> <script src="{% static "pages/js/all.js" %}"></script> <script src="{% static "pages/js/bootstrap.js" %}"></script> <script src="{% static "pages/js/main.js" %}"></script> This is in django, the first line <link rel="stylesheet" href="{% static "css/bootstrap.min.css" %}"/> and <script src="{% static "js/bootstrap.bundle.min.js" %}"></script> reference starts from the Child folder, where as all the other static files are loaded from the App folder; which is the parent. Can someone please elaborate this inconsistency in loading static files. -
Dynamic Tab names in Tabholder in Django-crispy-forms
I wondering is there any chance to use "dynamic" names for Tabs. Like in next example Tab names are hardcoded 'First Tab' and 'Second Tab' in ModelForm. I have dynamic titles (head1, 2 etc.) for every tabs and I am using values from database for titles. I like to use same text dynamically in tab names. Tab('First Tab', HTML("""<h4>{{ head1.0 }}</h4>"""), 'field_name_1', Div('field_name_2') ), Tab('Second Tab', HTML("""<h4>{{ head2.0 }}</h4>"""), Field('field_name_3', css_class="extra") ) I would like to add same dynamic title texts to tab names also like in next example, but I have not found solutions. Tab({{ head1.0 }}, HTML("""<h4>{{ head1.0 }}</h4>"""), 'field_name_1', Div('field_name_2') ), Tab({{ head2.0 }}, HTML("""<h4>{{ head2.0 }}</h4>"""), Field('field_name_3', css_class="extra") ) -
Amazon S3 Image not displaying
I'm implementing the Amazon S3 on an application I am about to deploy. I have this challenge. When I upload an image, it doesn't display on the site but if I open the image in a new tab, it displays properly. Please what do I do? This is my models.py file from django.db import models from django.utils import timezone from django.contrib.auth.models import User from PIL import Image class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics') def __str__(self): return f'{self.user.username} Profile' def save(self, *args, **kwargs): super(Profile, self).save(*args, **kwargs) # img = Image.open(self.image.path) # if img.height > 300 or img.width > 300: # output_size = (300, 300) # img.thumbnail(output_size) # img.save(self.image.path) This is what I added in the settings.py file AWS_ACCESS_KEY_ID = '**********' AWS_SECRET_ACCESS_KEY = '********' AWS_STORAGE_BUCKET_NAME = '********' AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = None DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' This is my views.py file def profile(request): #if request.user.is_verified(): if request.method == 'POST': u_form = UserUpdateForm(request.POST, instance=request.user) p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile) if u_form.is_valid() and p_form.is_valid(): u_form.save() p_form.save() messages.success(request, f'Your account has been updated') return redirect('profile') else: u_form = UserUpdateForm(instance=request.user) p_form = ProfileUpdateForm(instance=request.user.profile) context = { 'u_form': u_form, 'p_form': p_form } return render(request, 'users/profile.html', context) And this is the profile.html template {% … -
Can'not launch django installed inside docker
I am using Docker to launch my app which imports django. I want to do it inside my git repository. My Dockerfile looks like FROM python:3 WORKDIR /configurator CMD virtualenv -p python3.8 venv CMD . venv/bin/activate CMD pip install -U setuptools pip CMD pip install django COPY . /configurator/ CMD cd cconfigurator/ ENTRYPOINT /configurator/cconfigurator/manage.py runserver 8000 And I see an error: docker run configurator Traceback (most recent call last): File "/configurator/cconfigurator/manage.py", line 10, in main from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/configurator/cconfigurator/manage.py", line 21, in <module> main() File "/configurator/cconfigurator/manage.py", line 12, in main raise ImportError( ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? What am I doing wrong? -
Using an external API in Django
I'm trying to use an external API to grab data for my project to show on the template. service.py def get_data(title, url, description, body, datePublished): url = 'https://contextualwebsearch-websearch-v1.p.rapidapi.com/api/Search/WebSearchAPI' params = {"autoCorrect": "true", "pageNumber": "1", "pageSize": "10", "q": "police", "safeSearch": "true" } r = requests.get(url, params=params) data = r.json() article_data = {'data': data['value']} return article_data Then I show it on views.py ... import service class IndexData(TemplateView): def get(self, request): article_data = service.get_data.all() return render(request, 'pages/home.html', article_data) but I'm getting ModuleNotFoundError: No module named 'service' Did i miss something? -
How to build this complex form in Django with multiple models?
How should I build this complex form in Django? In particular, what I would like to accomplish is to be able to send the indented information making clear that it is inside and related to the parent option. In the example, I would like to send the information that the Antivirus within Malware is checked and that Malware - Antivirus has the criticality specified in the dropdown. Malware is from class Theat, Antivirus is from class Control and Malware-Antivirus-High is from class Requirement. And everything while creating a Subcategory. -
Why does my website take so long to load to browser?
So I have added a https to a simple website ( goenigmamusic.com ) built with django and you can only connect to it with a good internet connnection. The ssl certificate was done on aws, as well as the deployment. I have a metro pcs internet connection on my phone, I use it to test my website load time. Whats interesting is that, I can load a website like cartoonnetwork.com with a decent internet connection to my browswer, but goenigmamusic.com can't even load the website to my browswer, but when connected to good wifi? Why? -
Sending user-dependent scheduled emails with celery and django?
I'd like for my web-app to send weekly / monthly emails to the users - how would I limit celery to only send scheduled emails to the users that "opt-in"? I installed django-celery-beat and I can configure a cron job in the admin interface, but not only to specific users -
Getting "Method Not Allowed: /users/update_contact/"
This my javascript function intended to update my database. However, I get two errors: Method Not Allowed: /users/update_contact/" SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data function update_contact (){ url = "{% url 'users:update_contact' %}"; git_profile = prompt("enter git profile name") phone = prompt("enter phone number") email = prompt("enter email address") const contact = { "git_profile" : git_profile, "phone_number" : phone, "email" : email }; var stringify_contact = JSON.stringify(contact); const options = { method: 'POST', body: JSON.parse(stringify_contact), mode: 'same-origin', dataType: 'json', headers : { 'content-Type' : 'application/json', 'X-CSRFToken': csrftoken, } } fetch(url, options) .then(res => res.json()) .then(res => console.log(res)) } -
Django: Display database information to match the form? ValueError: .. didn't return an HttpResponse object. It returned None instead
I am trying to query the database to display results from the form. Once I select the form drop-down fields for my wanted query e.g. Ford C-Max 2019 1.2 Petrol 1500 , from which I coded for now to display results (regardless of Make & Model as I only have one atm) , then instead of showing me the table with matched results I get this error: Request Method: POST Request URL: http://127.0.0.1:8000/data/ Django Version: 3.0.3 Exception Type: ValueError Exception Value: The view app.views.data didn't return an HttpResponse object. It returned None instead. However I do have that result in the database table named ford_cmax (ignore the average & entered columns) average entered year liter fuel mileage 9701 2020-04-08 20:59:45 2019 1.2 Petrol 1500 I did not have this problem before, the table showed all results fine before I did the tweaking for filters. My code: views.py from django.shortcuts import render from django.http import HttpResponse from django.views.generic import FormView from django.db.models import Q from .models import Average, Query from .forms import QueryForm class QueryMakeModel(FormView): template_name = 'QueryMakeModel.html' success_url = '/data/' form_class = QueryForm def form_valid(self, form): return HttpResponse("Sweet.") def index(request): if request.method == 'POST': FormSite = QueryForm(request.POST) if FormSite.is_valid(): pass … -
Django the fastest way to do Query get list of items in row from table
In my app I need to do fast Query but I don't know which is faster materials = Material.objects.only('name') Or do filter this in view materials = Material.objects.all() And then use for loop to show list of items from 'name' row I think that first is better or there is better way to do this? It cant be done with filter() because it need to show all of fields in this row. -
Pass a file path as a URL parameter in Django
I'm using Django to create a webapp. When a user press on a certain button, it needs to pass a file path as parameter and a string parameter to one of my views. I can't simply use the parameter in the URL since the path contains several '/'. The way I have it setup right now is as follows: parameters.py ''' class FilePathConverter: regex = '^[/]' def to_python(self, value): value=str(value) return value.replace("?", "/") def to_url(self, value): value=str(value) return value.replace("?", "/") urls.py from django.urls import path from . import views from django.contrib import admin from django.views import generic from django.urls import path, register_converter from . import converters, views register_converter(converters.FilePathConverter, 'filepath') urlpatterns = [ path('', views.index, name='webpanel-index'), path('controlserver/<str:server_path>/<str:control>', views.index, name='controlserver'), ] views.py from django.shortcuts import render from django.http import HttpResponse from .models import Server from django.contrib.auth.decorators import login_required import subprocess def controlserver(request, server_path, control): if request.POST: subprocess.call(['bash', server_path, control]) return render(request, 'index.html') However, with this method, I get this error: Reverse for 'controlserver' with keyword arguments '{'server_path': 'rien/', 'control': 'start'}' not found. 1 pattern(s) tried: ['controlserver/(?P<server_path>[^/]+)/(?P<control>[^/]+)$'] -
Problems in multiple page form
I created a function for creating Course object.Form works but i don't know how to create Course object here.How to do that? views.py class FormWizardView(SessionWizardView): template_name = 'courses/create_course.html' file_storage = FileSystemStorage(location=os.path.join(settings.MEDIA_ROOT,'courses')) def done(self, form_list, **kwargs): data = {k: v for form in form_list for k, v in form.cleaned_data.items()} instance = Course.objects.create(**data) return render(self.request, 'courses/done.html',{'form_data': [form.cleaned_data for form in form_list],}) urls.py path('create_course/',FormWizardView.as_view([CourseForm1,CourseForm2.CourseForm3,CourseForm4]),name='create_course'), -
I want request.POST[variable name] to be executed only if the variable name exists in the input of template
def sendorder(request): items = MenuModel.objects.all() if request.method == 'POST': for item in items: if request.POST['item'+str(item.id)]: print(request.POST['item'+str(item.id)]) return I have some inputs in templates with name item2,item3 etc etc, but this view counts right from the beginning item1 which gives error as no input with name item1 exists. I want to bypass if no such input name exists. -
Prefech many to many relation for one class instance
I want to limit the queries for a detail view. I want to access multiple many to many fields for one class instance. It seems prefetch_related doesn't work with get. JobInstance = Job.objects.get(pk=id).prefetch_related('cities').prefetch_related('experience_level') -
Django custom paginator fails to catch non integer value
I want to use my own Paginator in view based on ListView. The need for custom Paginator is coming from two user errors I want to catch: too big number and no number. There is no problem in catching the first issue with EmptyPage error. What I have problem with is no number error - e.g. ?page=k From documentation I would assume this can be achieved with PageNotAnInteger, or both with InvalidPage. So this is what I did: class SafePaginator(Paginator): def validate_number(self, number): try: return super(SafePaginator, self).validate_number(number) except InvalidPage: return 1 Unfortunately, still when I test ?page=k option I'm getting error: Page is not 'last', nor can it be converted to an int. ?page=last is working correctly This seems to be coming from ListView paginate_queryset as you can see on GitHub def paginate_queryset(self, queryset, page_size): """Paginate the queryset, if needed.""" paginator = self.get_paginator( queryset, page_size, orphans=self.get_paginate_orphans(), allow_empty_first_page=self.get_allow_empty()) page_kwarg = self.page_kwarg page = self.kwargs.get(page_kwarg) or self.request.GET.get(page_kwarg) or 1 try: page_number = int(page) except ValueError: if page == 'last': page_number = paginator.num_pages else: raise Http404(_('Page is not “last”, nor can it be converted to an int.')) try: page = paginator.page(page_number) return (paginator, page, page.object_list, page.has_other_pages()) except InvalidPage as e: raise Http404(_('Invalid page … -
How can I display Number in a Django Template
I have a list of Entries Generated from my Database and displayed on the template as seen below. {% for post in blog_post %} <tr> <td> S/N </td> <td><a href="{% url 'webpages:articles_detail' post.slug post.pk %}"> {{post.title}}</a></td> <td>{{post.created_on | date:"Y-m-d" }}</td> </tr> {% endfor %} How can I automatically display and increament the serial number part (labelled S_N) -
Server keep looping because of this code and I don't know why?
I want to save a second version of thumbnail field where the second version [thumbnail_low] resolution is 320 * 200 because I want my list view run faster. in creation form I accept image where the size is up to 5 megabytes and i don't want to load 5 megabytes per post. Sorry for mistakes i'm a french guy. f = BytesIO() try: copy.thumbnail((320, 200), Image.ANTIALIAS) copy.save(f, format="JPEG") b = f.getvalue() self.thumbnail_low.save("thumb", ContentFile(b)) finally: f.close() -
Error when creating an admin for the database Python (django)
1 You did not provide an API key. You need to provide your API key in the Authorization header, using Bearer auth (e.g. 'Authorization: Bearer YOUR_SECRET_KEY'). this error POPs up after 33 minutes of the tutorial: https://www.youtube.com/watch?v=zu2PBUHMEew After creating STRIPE_SECRET_KEY error when creating a superuser it was at 33 minutes approximately before that everything was fine . Help me find a solution ) -
Django/JS - Can't set default value for an already liked post
I want to check conditional on each post if the logged in user has liked it or not, accordingly I want to pass in a context which assigns the button a CSS class for the default value of color when the page loads. I don't want to use to use HTML if/else condition as I'm using JavaScript to change the color of the button when clicked. Even though I'm able to change the color once I click but I'm stuck at how to pass in the default condition of the post whenever the page loads. This is the JavaScript code : window.onload = function(){ var thumb_up = document.getElementById('thumb_up'); thumb_up.style.cursor = 'pointer'; thumb_up.onclick = function(){ var req = new XMLHttpRequest(); var id = this.getAttribute('data-id'); var url = '/api/like/'+id+'?format=json'; req.onreadystatechange = function(){ if(this.readyState==4 && this.status==200){ // var data = eval(req.responseText); data = JSON.parse(req.responseText); var likes = data.likes; document.getElementById('likes-count').innerHTML = likes+' votes'; //changing color if(data.liked=='true'){ thumb_up.className = "material-icons thumb_up_liked"; } else{ thumb_up.className = "material-icons thumb_up"; } } }; req.open("GET", url, true); req.send(); } } Also, I tried sending the default value for CSS/HTML class from backend, but I'm messing up the syntax. Can't figure out the logic to send it from backend either. … -
Configuring SSL Certificate for Django application on Apache using WAMP and mod_wsgi on Windows machine
I want to host a django web application on Apache server for which Im using WAMP server. The website is hosted and working fine but Im facing issues when Im installing SSL certificate. When I run as the intended website is shown appropriately instead it should have redirected to https://localhost and if I type https://localhost Forbidden You don't have permission to access this is shown httpd-vhosts.conf file: <VirtualHost *:80> ServerName localhost WSGIPassAuthorization On ErrorLog "C:/Django/my_project/my_project.error.log" CustomLog "C:/Django/my_project/my_project.access.log" combined WSGIScriptAlias / "C:/Django/my_project/my_project/wsgi_windows.py" <Directory "C:/Django/my_project/my_project"> <Files wsgi_windows.py> Require all granted </Files> </Directory> httpd.conf file: Here I have commented out these three lines Loadmodule ssl_module modules/mod_ssl.so, Include conf/extra/httpd-default.conf and LoadModule socache_shmcb_module modules/mod_socache_shmcb.so # configuration directives that give the server its instructions. # See <URL:http://httpd.apache.org/docs/2.4/> for detailed information. # In particular, see # <URL:http://httpd.apache.org/docs/2.4/mod/directives.html> # for a discussion of each configuration directive. # # Do NOT simply read the instructions in here without understanding # what they do. They're here only as hints or reminders. If you are unsure # consult the online docs. You have been warned. # # Configuration and logfile names: If the filenames you specify for many # of the server's control files begin with "/" (or "drive:/" for Win32), … -
Django: Show posts with maximum upvotes
I am working on a project and I am a beginner in Django. In the project, the user can create product posts and other users can upvote it. On the homepage, I wanna show posts with maximum upvotes. I am using Postgresql as a backend. this is the view function for the homepage that returns products dictionary: def home(request): products = Product.objects return render(request, 'products/home.html', {'products': products}) as I am a beginner I am not getting any idea of how to do it in Django templates.