Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I am facing myapp not found problem in Django-Heroku
Its my first heroku-Django project. Its working fine locally But when I tired to run on heroku, it deployed successfully, but shows the error in gunicorn (since I am using windows) So, I used 'waitress-serve --listen=*:8000 myapp.wsgi:application' in place of gunicorn. it again deployed successfully, but not working on heroku. It is Showing the error of "There was an exception (ModuleNotFoundError) importing your module. ", "No module named 'myapp'" in heroku logs. Please suggest a solution Thanks -
How to display or render multiple forms in django
I'm currently working on a personal project where in a page (purchases page), there will be the main form (includes product name, product category and product specifications fields). now, there is a link "Add New Product Category" that activates the modal. This modal includes a separate form. What you are seeing is the final output or what I want the page to be, i only did that in html, no django coding involve. My (stupid) question is, how am i going to display BOTH forms? I don't understand how {{form}} works. I successfully rendered the productCategoryForm in the modal by using the code {{form}} but when I do the same in the second form productDetailsForm it's not rendering or displaying. It's blank. I'm not sure how is this going to work. Below is my Views.py and Forms.py codes. Views.py def addNewCategory(response): if response.method == "POST": form = productCategoryForm(response.POST) if form.is_valid(): a = form.cleaned_data["productCateg"] b = productCategory(productCat=a) b.save() return HttpResponseRedirect("/acctg/purchases/") else: form = productCategoryForm() return render(response, 'purchases.html', {"form": form}) def addNewProduct(response): form = productDetailsForm(response.POST) return render(response, 'purchases.html', {"form": form) Forms.py class productCategoryForm(forms.Form): productCateg = forms.CharField(label="Product Category", max_length=100, required=True, widget= forms.TextInput(attrs={'class':'form-control col-sm-8 col-form-label'})) class productDetailsForm(forms.Form): productName = forms.CharField(label="Product Name", max_length=100, required=True, widget= … -
Heroku site throws ModuleNotFoundError: No module named 'config'
I am using Pycharm and django to launch a test website on heroku but the site shows an Application Error: Heroku Log: (venv) C:\Users\Artur\PycharmProjects\dfb2_home_about\pages>heroku logs 2021-06-25T06:27:56.488118+00:00 app[web.1]: return self.load_wsgiapp() 2021-06-25T06:27:56.488119+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/app/wsgiapp.py", line 48, in load_wsgiapp 2021-06-25T06:27:56.488119+00:00 app[web.1]: return util.import_app(self.app_uri) 2021-06-25T06:27:56.488120+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/util.py", line 359, in import_app 2021-06-25T06:27:56.488120+00:00 app[web.1]: mod = importlib.import_module(module) 2021-06-25T06:27:56.488121+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/importlib/__init__.py", line 127, in import_module 2021-06-25T06:27:56.488121+00:00 app[web.1]: return _bootstrap._gcd_import(name[level:], package, level) 2021-06-25T06:27:56.488122+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1014, in _gcd_import 2021-06-25T06:27:56.488122+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 991, in _find_and_load 2021-06-25T06:27:56.488122+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 961, in _find_and_load_unlocked 2021-06-25T06:27:56.488123+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed 2021-06-25T06:27:56.488123+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1014, in _gcd_import 2021-06-25T06:27:56.488124+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 991, in _find_and_load 2021-06-25T06:27:56.488124+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked 2021-06-25T06:27:56.488124+00:00 app[web.1]: ModuleNotFoundError: No module named 'config' 2021-06-25T06:27:56.488217+00:00 app[web.1]: [2021-06-25 06:27:56 +0000] [8] [INFO] Worker exiting (pid: 8) 2021-06-25T06:27:56.524674+00:00 app[web.1]: [2021-06-25 06:27:56 +0000] [4] [INFO] Shutting down: Master 2021-06-25T06:27:56.524822+00:00 app[web.1]: [2021-06-25 06:27:56 +0000] [4] [INFO] Reason: Worker failed to boot. 2021-06-25T06:27:56.639146+00:00 heroku[web.1]: Process exited with status 3 2021-06-25T06:27:56.714706+00:00 heroku[web.1]: State changed from starting to crashed 2021-06-25T06:27:56.718477+00:00 heroku[web.1]: State changed from crashed to starting 2021-06-25T06:28:01.999568+00:00 heroku[web.1]: Starting process with command … -
MultiValueDictKeyError at edit
I writing a code for my class to create a list from users input. on the list there is an option for editing each entries; however when i click on my edit bottom i get multi value error. Could anyone please let know how to fix this error? My html part for the list: Your wish list: <table> <thead style="background-color: rgb(226, 220, 220)"> <th>Item</th> <th>Date added</th> <th>Actions</th> </thead> <tbody> {% for wish in all_wishes %} <tr> <td><h5><a href="/wishes/{{wish.id}}">{{wish.wish}}</a></h5></td> <td> Added on {{wish.created_at}} </td> <td> <a href="/wishes/{{wish.id}}/delete" role="button">Remove</a> | <a href="/wishes/{{wish.id}}/edit">Edit</a> | <a href="/wishes/{{wish.id}}/granted" role="button">Granted!</a> </td> </tr> {% endfor %} </tbody> </table> My urls: I removed other urls to make it clean here from django.urls import path from .import views urlpatterns = [ path("wishes/<int:wish_id>/edit", views.edit), ] my views.py (edit part): def edit(request, wish_id): wish = Wish.objects.get(id=wish_id) wish.description = request.POST['description'] wish.save() return redirect("wishes/showall.html") redirect to html on top My Model: class Wish(models.Model): description = models.CharField(max_length=255) My error message: MultiValueDictKeyError at /wishes/32/edit 'description' Request Method: GET Request URL: http://localhost:8000/wishes/32/edit Django Version: 2.2 Exception Type: MultiValueDictKeyError Exception Value: 'description' C:\Users\wishlist_app\views.py in edit wish.description = request.POST['description'] -
Django display selected multi checkbox on template
I have a form with multi checkbox selection and a template that displays the form (with some additional styling so the checkboxes are in a dropdown). I want to display the selected by the user checkboxes next to the field. How do I access the selected values from the field in my template? Form: class ReadData(forms.Form): def __init__(self, elems, *args, **kwargs): super().__init__(*args, **kwargs) for i, elem in enumerate(elems): self.fields['class-%d' % i] = forms.MultipleChoiceField(label='Select', widget=forms.CheckboxSelectMultiple, choices=CHOICES, required=False) Template: {% for form in form.visible_fields %} <div class="field-element"> <button class="btn btn-stereo dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> <label>{{ form.label_tag}}</label> </button> <div class="dropdown-menu" aria-labelledby="dropdownMenuButton"> <div class="list-stereo">{{form}}</div> </div> </div> -
Why use aggregate to find average value instead of using tutal_sum/n in django
Here we calculate using aggregate >>> avg = Book.objects.aggregate(average_price=Avg('price')) {'average_price': 34.35} But why we don’t use below concept in above. a = Books.objects.all() Avg = sum([x.price for x in a])/len(a) 34.35 I want to know use aggregate rather than second procees. -
'UserManager' object has no attribute 'validate'
My usual registration and login validators stopped working and I'm banging my head against the wall trying to figure out why. This is the error: AttributeError at /register 'UserManager' object has no attribute 'validate' Models.py class UserManager(models.Manager): def validate(self, postData): errors = {} if len(postData['first_name']) < 3: errors['first_name'] = 'First Name must be at least 2 characters' if len(postData['last_name']) < 3: errors['last_name'] = 'Last Name must be at least 2 characters' EMAIL_REGEX = re.compile(r'^[a-zA-Z0-9.+_-]+@[a-zA-Z0-9._-]+\.[a-zA-Z]+$') if not EMAIL_REGEX.match(postData['email']): errors['email'] = "Invalid email address!" email_check=User.objects.filter(email=postData['email']) if email_check: errors['email'] = ("Email address already taken!") if len(postData['password']) < 8 : errors['password'] = 'Password must be at least 8 characters' if postData['password'] != postData['confirm_password']: errors['password'] = 'Passwords do not match' return errors views.py def register(request): if request.method == "GET": return redirect('/') errors = User.objects.validate(request.POST) if errors: for e in errors.values(): messages.error(request, e) return redirect('/') else: new_user = User.objects.register(request.POST) request.session['user_id'] = new_user.id return redirect('/profile') -
Django template text to views. Py
Is there any way in django to extract the text inside any paragraph of template to the django views. Py file. Or If there is no post and get method. -
i am using django to return file as response but i want to return mutiple files or zip how i can do it [duplicate]
here is the simple code where after returning 1 files the function get returned how can we make it recursive or any help. @login_required(login_url="/login/") def download(request): FileData = File.objects.filter(project=projectId) for i in FileData: filePath = settings.MEDIA_ROOT+i.files with open(filePath,"rb") as fh: response = HttpResponse(fh.read(),content_type="application/files") response["Content-Disposition"]= "inline;filename="+os.path.basename(filePath) return response return HttpResponse("something error") -
Why my model field doesn't read the value of its ForeignKey, it returns its object number instead?
I created a model which has a field which I want to be a dynamic dropdown. I created another model and related them with a Foreign Key. Now everything works fine except the dropdown doesn't show the values from the other model, instead it returns its numbered objects. Here is my models.py: from django.db import models from django.core.validators import RegexValidator from django.db.models.deletion import CASCADE # Create your models here. class Diagnosis(models.Model): diagnosis=models.CharField(max_length=30, blank=True) class InitialData(models.Model): pattern = RegexValidator(r'RT\/[0-9]{4}\/[0-9]{2}\/[0-9]{4}', 'Enter RT Number properly!') pattern1 = RegexValidator(r'OOPL\/D\/00[0-9]', 'Enter Case Number properly!') case_number=models.CharField(max_length=10, primary_key=True, unique=True, validators=[pattern1], blank=True) date_of_admission=models.DateField(default=None) date_of_discharge=models.DateField(default=None) name=models.CharField(max_length=100, default=None) mr_uid=models.IntegerField(default=None) rt_number=models.CharField(max_length=15, blank=False, validators=[pattern], default=None) diagnosis=models.ForeignKey(Diagnosis, on_delete=CASCADE) forms.py: class TrackReportForm(ModelForm): class Meta: model=InitialData fields=('case_number', 'date_of_admission', 'date_of_discharge', 'name', 'mr_uid', 'rt_number', 'diagnosis') class DiagnosisForm(ModelForm): class Meta: model=Diagnosis fields=('diagnosis',) views.py: def initialview(request): if request.method=='POST': fm_diagnosis=DiagnosisForm(request.POST) fm_initialdata=TrackReportForm(request.POST) if fm_diagnosis.is_valid() and fm_initialdata.is_valid: diagnosis=fm_diagnosis.save() initial=fm_initialdata.save(False) initial.diagnosis=diagnosis initial.save() fm_diagnosis=DiagnosisForm() fm_initialdata=TrackReportForm() return render(request, 'account/database.html', {'form1':fm_diagnosis, 'form2':fm_initialdata}) else: fm_diagnosis=DiagnosisForm() fm_initialdata=TrackReportForm() return render(request, 'account/database.html', {'form1':fm_diagnosis, 'form2':fm_initialdata}) URLs: from account import views urlpatterns = [ path('admin/', admin.site.urls), path('data/', views.initialview), ] template: <body> <form action="" method="post" novalidate> {% csrf_token %} {{form1.as_p}} {{form2.as_p}} <button type="submit">Save</button> </form> </body> What needs to be changed? -
how to verify username and password at the time of login where existing password is encrypted by make_password which is stored in database?
I have register username and password using the following code views.py def registerPage(request): if request.method == 'POST': form = AdminUserForm(request.POST) Password = request.POST['Password'] if form.is_valid(): user = form.save(commit=False) user.Password = make_password(Password) user.save() messages.success(request, "user created succesfully!!! login now") return redirect('login') else: form = AdminUserForm() return render(request, 'signup.html', {'form': form}) Can someone tell me how to verify username and password while login, and logout? models.py class AdminUser(models.Model): Id=models.AutoField(primary_key=True) Name=models.CharField(max_length=100, null=False, blank=False) Username=models.CharField(max_length=100, null=False, blank=False) Password=models.CharField(max_length=100, null=False, blank=False) class Meta: db_table='admin_users' forms.py class AdminUserForm(forms.ModelForm): class Meta: model= AdminUser fields = '__all__' thanks in advance, please help in login and logout -
Why try except not works in django filter?
Here is my filter class: class PackageFilter(django_filters.FilterSet): regex = django_filters.CharFilter(method="regex_filter") class Meta: model = models.Package fields = { 'package': ['exact'], } def regex_filter(self, queryset, _, value): try: return queryset.filter(package__regex=value) except: raise ParseError('{} is invalid regex!'.format(value)) when i deliver python-2.\d+* to backend backend should return 400 python-2\.\d+* is invalid regex! but actually not, it return File "/usr/local/lib/python3.6/dist-packages/django/db/backends/utils.py" in _execute 85. return self.cursor.execute(sql, params) File "/usr/local/lib/python3.6/dist-packages/django/db/utils.py" in exit 89. raise dj_exc_value.with_traceback(traceback) from exc_value File "/usr/local/lib/python3.6/dist-packages/django/db/backends/utils.py" in _execute 85. return self.cursor.execute(sql, params) Exception Type: DataError at /api/v3/packages/ Exception Value: invalid regular expression: quantifier operand invalid -
Getting multiple textfield values - Javascript/Django
This is my code. I'm trying to get all the values from the dynamically generated textboxes so that I can average them and will use the value later. Is there any easy way to get all the values and their average? for(var i = 0; i < input_list.length -1; i++) { var label_input = document.createElement('label'); label_input.innerHTML = input_list[i+1]; document.getElementById("newElementId").appendChild(label_input); for(var j = 0; j < 5; j++) { $('#newElementId').append("<div><input type='textbox' id='"+ input_list[i+1] + j +"' /></div>"); } } -
Why do some model objects reset every time i redeploy and after a while of time passes in Django Heroku?
This is probably a really dumb question. Every time I redeploy my django app on heroku i get the same two instances of my object that were there before i deployed. I would like to change these. I would like to add some. I would like to delete some. But every time I redeploy, and after some time passes after I make changes, it always reverts back to what it was. It is horrible. Please let me know what I am doing wrong. NOTE: I AM ALREADY HOLDING MY FILES SOMEWHERE ELSE. I don't believe this has anything to do with the ephemeral file system, since I already am storing files somewhere else. But why is it that every time I redeploy the instances of the objects themselves (instances of the things inside Models) go away?? Thanks in advance. -
'TypeError' object has no attribute ''
I am using SendGrid with Django and I have two separate functions. One works using the SendGrid code (See below - Working Code) and then the other keeps getting the Error - 'TypeError' object has no attribute 'booking_message'. I imagine the issue is something small and I keep missing it. Appreciate any help I can get on this. (Note - I have taken out the template id's, From and to email addresses and SendGrid API App id and just let '') I did not have time to use an environment variable to hide the keys before posting. Working code class ASPBookingsCreateView(CreateView): form_class = ASPBookingsForm model = ASPBookings template_name = "vistours/asp.html" def post(self, request): # Save the new booking to the database. if request.method == 'POST': form = ASPBookingsForm(request.POST) if form.is_valid(): print(request.POST) form.save() # Get the data for the emails. asp_data = ASPBookings.objects.all() asp_data.contact_name = request.POST['contact_name'] asp_data.booking_email = request.POST['email'] asp_data.booking_date = request.POST['booking_date'] asp_data.booking_time = request.POST['booking_time'] asp_data.program_type =request.POST['program_type'] # Format Date and Time formatted_date = parse_date(asp_data.booking_date).strftime('%A %d %B %Y') print(formatted_date) # Add SendGrid Template ID's BOOKING_TEMPLATE_ID = '' UPDATE_TEMPLATE_ID = '' # Send confirmation email of the booking. booking_message = Mail(from_email='', to_emails=[asp_data.booking_email], ) # Add Template ID to booking message. booking_message.template_id = … -
how do I produce m2m model from sql schema?
I am new with django ecosystem where I want to create the following tables from SQL to django model syntaxis where I got stuck at how to produce this proxy table tools_x_techniques as m2m CREATE TABLE tools_x_techniques ( # m2m id INTEGER PRIMARY KEY AUTOINCREMENT, tool_id TEXT NOT NULL, technique_id TEXT NOT NULL, FOREIGN KEY (tool_id) REFERENCES tools (id), FOREIGN KEY (technique_id) REFERENCES technique (id) ); CREATE TABLE tools ( id INTEGER PRIMARY KEY AUTOINCREMENT, tool_id TEXT NOT NULL, ); CREATE TABLE techniques ( id INTEGER PRIMARY KEY AUTOINCREMENT, technique_id TEXT NOT NULL, ); django class Techniques(models.Model): technique_id = models.TextField() class Tools(models.Model): tool_id = models.TextField() -
ERROR: Command errored out with exit status 1: 'import sys, setuptools, tokenize; sys.argv[0]
how to solve this problem. I am tried to solve the error can't properly deploy my Django project on Heroku build logs: | ^~~~~~~~~~~~~~~~~~~~~ error: command '/usr/bin/gcc' failed with exit code 1 ---------------------------------------- ERROR: Command errored out with exit status 1: /app/.heroku/python/bin/python -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-zu1munoh/typed-ast/setup.py'"'"'; __file__='"'"'/tmp/pip-install-zu1munoh/typed-ast/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record /tmp/pip-record-s15khtlb/install-record.txt --single-version-externally-managed --compile --install-headers /app/.heroku/python/include/python3.9/typed-ast Check the logs for full command output. ! Push rejected, failed to compile Python app. ! Push failed Procfile web: gunicorn My_Ecom_Project.wsgi -
Server Request Interrupted Heroku
I am using React Native and Django. Everything was working fine, until I made a request and I got the following error: sock=backend at=error code=H18 desc="Server Request Interrupted" method=POST path="/api/obtain-img" host=notarealapp.herokuapp.com request_id=... fwd="..." dyno=web.1 connect=0ms service=22ms status=503 bytes=316 protocol=https Also, I don't know if this is useful information, but I got the following error too: <rest_framework.request.Request: POST '/api/obtain-img'> The fetch code I used is this: let token = await SecureStore.getItemAsync("token"); console.log(uri); let filename = uri.split("/").pop(); let match = /\.(\w+)$/.exec(filename); let type = match ? `image/${match[1]}` : `image`; let formData = new FormData(); formData.append("image", { uri: uri, name: filename, type: type }); // formData.append("cateogry", category); // formData.append("mission", value); console.log(formData); return await fetch("https://notarealapp.herokuapp.com/api/obtain-img", { method: "POST", headers: { "content-type": "multipart/form-data", Authorization: `JWT ${JSON.parse(token)}`, }, body: formData, }) .then((res) => res.json()) .then((json) => console.log(json)) .catch((error) => console.error(error)); And my Django code is the following: class ObtainImageUri(APIView): permission_classes = [IsAuthenticated] def post(self, request, format=None): print(request) return Response({"succes": "The receipt was stored successfully."}, status=200) I am open to any help. Thank you -
IntegrityError: UNIQUE constraint failed: auth_user.username - Django
I have a sample application that simply logs in and registers users. I am adding functionality for checking whether a username is already taken. For that, in the form code, I put a validation function as is usual in django. It's called clean_username. There are also functions like clean_email and clean to check the sanity of data. While the other two work just fine to weed duplicates, the clean_username function is particularly erroneous. Though I have added a line to check whether the username already exists, it still throws the same Integrity Error, which is exactly what I am trying to avoid. The clean_username function is of our concern here. Note: The print statements are only added for debugging purposes. Please find the code below (forms.py): from django import forms from django.forms.widgets import Widget from django.contrib.auth import get_user_model from email_validator import validate_email, EmailNotValidError from .constants import countries User = get_user_model() class RegisterForm(forms.Form): login = forms.CharField(label="Username:") password = forms.CharField(label="Password", widget=forms.PasswordInput()) confirm_password = forms.CharField(label="Confirm Password:", widget=forms.PasswordInput()) email = forms.EmailField(label="Email") def clean_username(self): print(f"Clean Username data: {self.cleaned_data}") username = self.cleaned_data.get("login") print("cleaning username...") existing_user_set = User.objects.filter(username=username) if existing_user_set.exists(): raise forms.ValidationError("Username is taken!!") return username def clean(self): data = self.cleaned_data print(f"\n\nData from cleaned data: {data}") password … -
Include a .html file in Django template that is located in a different directory
Let's say I have the following directory structure |-data |-include_this.html |-app |- templates |- app |- page.html In page.html, I'd like to include the include_this.html file contained in the data folder. I have tried the following: {% include '../data/papercups.html' %} {% include '../../data/papercups.html' %} {% include './../data/papercups.html' %} But none of them seem to work, and the second one throws the error: The relative path points outside the file hierarchy that template is in. What's the correct way to do this? -
axios wont retrieve data from django server
I try to retrieve data from my django server to render it with react but I encountered a probem: The data doesen't render. I have my django server running in localhost:8000 and react app running in localhost:3000 my App.js: import React from 'react'; import axios from 'axios'; class App extends React.Component { state = { details : [], } componentDidMount() { let data ; axios.get('http://localhost:8000/wel/') .then(res => { data = res.data; this.setState({ details : data }); }) .catch(err => {}) } render() { return( <div> {this.state.details.map((detail, id) => ( <div key={id}> <div > <div > <h1>{detail.detail} </h1> <footer >--- by <cite title="Source Title"> {detail.name}</cite> </footer> </div> </div> </div> ) )} </div> ); } } export default App; and my server page where I try to retrieve data from: localhost:8000/wel what's going on? -
Redis Error condition on socket for SYNC: Connection refused
Using celery with redis in my django app Everything was working fine until I ran into a problem. The location of the redis files was changed and redis could not access them. After searching, it turns out that this is due to random attacks on the Internet, and it is necessary to add confg After I added the file, they both worked fine for a while, and then this problem appeared 1:S 25 Jun 2021 00:48:12.029 # Error condition on socket for SYNC: Connection refused 1:S 25 Jun 2021 00:48:12.901 * Connecting to MASTER 194.38.20.199:8886 1:S 25 Jun 2021 00:48:12.902 * MASTER <-> REPLICA sync started 1:S 25 Jun 2021 00:48:13.034 # Error condition on socket for SYNC: Connection refused 1:S 25 Jun 2021 00:48:13.907 * Connecting to MASTER 194.38.20.199:8886 1:S 25 Jun 2021 00:48:13.908 * MASTER <-> REPLICA sync started 1:S 25 Jun 2021 00:48:14.041 # Error condition on socket for SYNC: Connection refused When I rebuild the Redis container it runs for a very short time and I get the same problem settings.py CELERY_BROKER_URL = os.environ.get("redis://redis:6379/0") CELERY_RESULT_BACKEND = os.environ.get("redis://redis:6379/0") docker-compose.yml redis: image: 'redis:alpine' restart: unless-stopped command: redis-server /usr/local/etc/redis/redis.conf volumes: - ./docker/redis/redis.conf:/usr/local/etc/redis/redis.conf ports: - '6379:6379' celery: restart: unless-stopped build: … -
How to allow only a certain section of my code to reload in Django
So, I am using a Django application where I am using the google maps API as well. So this is the instance...when I submit a form... I only want my form div to reload and NOT the div where my map lies. So my code is... <section class="middleSection p-2"> <div class="HideOpenMiddleCont justify-content-center" onclick="HideOpenMiddleCont()"> <div class="px-4 rounded-pill bg-warning" id="arrowCont"> <svg xmlns="http://www.w3.org/2000/svg" width="25" height="25" fill="currentColor" class="bi bi-arrow-down-short text-dark" viewBox="0 0 16 16"> <path fill-rule="evenodd" d="M8 4a.5.5 0 0 1 .5.5v5.793l2.146-2.147a.5.5 0 0 1 .708.708l-3 3a.5.5 0 0 1-.708 0l-3-3a.5.5 0 1 1 .708-.708L7.5 10.293V4.5A.5.5 0 0 1 8 4z"/> </svg> </div> </div> {% if view == 'trip' %} {% include "app/passenger/trip.html" %} {% elif view == "upcomingRides" %} {% include "app/passenger/upcomingRides.html" %} {% elif view == "pastRides" %} {% include "app/passenger/pastRides.html" %} {% endif %} <div class="optionBarPull" data-bs-toggle="offcanvas" href="#offcanvasExample" role="button" aria-controls="offcanvasExample"> <svg xmlns="http://www.w3.org/2000/svg" width="30" height="30" fill="currentColor" class="bi bi-arrow-right-circle-fill" viewBox="0 0 16 16"> <path d="M8 0a8 8 0 1 1 0 16A8 8 0 0 1 8 0zM4.5 7.5a.5.5 0 0 0 0 1h5.793l-2.147 2.146a.5.5 0 0 0 .708.708l3-3a.5.5 0 0 0 0-.708l-3-3a.5.5 0 1 0-.708.708L10.293 7.5H4.5z"/> </svg> </div> </section> <section class="rightSection" id="map"> <h3 class="font3 text-center p-2"><strong>Google Maps is here</strong></h3> <h4 class="font3 text-center … -
JavaScript variable doesn't loop through Django model
Topic is a CharField, summary is TextField within topic. For some reason, the JavaScript doesn't loop through summary TextField -- it just uses the very first summary TextField and simply ignores the rest. I want every summary TextField to looped through and displayed. Not just the first one. Does this make sense? Something is wrong with my JavaScript code. As you can see in the image -- second topic's (Bitcoin) summary is missing (highlighted in red) Image displaying the problem on the webpage {%for topic in topics%} <script> var i = 0; var txt = '{{topic.summary}}'; function typeWriter() { if (i < txt.length) { document.getElementsByClassName('js-typewrite')[0].innerHTML += txt.charAt(i); i++; setTimeout(typeWriter, 65); } } setTimeout(typeWriter, 1000); </script> <body> <p class="content"> <span class="typewrite anim-typewrite js-typewrite"></span> </p> </body> </div> <div id = 'mpost-text'> {{topic.text|linebreaks}} </div> <div id = 'change-text'> {%if topic.owner == request.user and user.is_authenticated %} <a href = "{%url 'new_sites:post_edit' topic.id%}">Edit entry</a> <a href = "{%url 'new_sites:delete_post' topic.id%}">Delete topic</a> {% endif %} </div> </div> {%empty%} <li>No topics have been added yet.</li> {% endfor %} {%if user.is_authenticated%} <a href="{% url 'new_sites:new_post'%}">Add Post</a> {%endif%} {%endblock%} -
loading local files in django
I have a folder in c:\images, images here are updated by another app. Then I wanted a Django application to read those images on the admin site. The django applicationis sitting in c:\inetpub\wwwroot\myapp I have tried adding below lines in settings.py CURRENT_PATH = os.path.abspath(os.path.dirname(__file__)) MEDIA_ROOT = os.path.join(CURRENT_PATH, '../../images').replace('\\','/') MEDIA_URL = 'images/' I also tried including the whole path in django admin as below in admin.py def img_field(self, obj): return format_html('<img src="{}" width="500" height="500" />'.format("c:\images\phot1.png")) If i put online image link it works fine as below: def img_field(self, obj): img = "https://www.thebalancesmb.com/thmb/5G9LJXyFzbTVS-Fj_32sHcgJ8lU=/3000x0/filters:no_upscale():max_bytes(150000):strip_icc():format(webp)/start-online-business-with-no-money-4128823-final-5b87fecd46e0fb00251bb95a.png" return format_html('<img src="{}" width="500" height="500" />'.format(img)) How can i get around this?