Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why i am getting ValueError?
model.py class User(models.Model): ImageKitConf.CACHEFILE_DIR = 'uploads/200/' first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=20) username = models.CharField(max_length=30, unique=True) password = models.CharField(max_length=100) email = models.EmailField(unique=True) phone = models.CharField(max_length=20) address = models.CharField(max_length=100) photo = models.ImageField(upload_to='uploads/200/', default='uploads/200/default.png', blank=True) thumb = ImageSpecField( source=photo, processors=[SmartResize(200,200)], ) role = models.ForeignKey('Role', default=3, on_delete=models.CASCADE) is_active = models.BooleanField(default=True) activation_code = models.CharField(max_length=50) password_reset_code = models.CharField(max_length=50, default=0) form.py class Registration_Form(forms.ModelForm): CHOICES = [('1', 'Active',), ('0', 'Inactive',)] is_active = forms.ChoiceField(label='Is Active', choices=CHOICES, required=True, widget=forms.RadioSelect()) user_title = forms.ModelChoiceField(label='User Role', empty_label='--- Select a Role ---',queryset=Role.objects.all() , widget=forms.Select(attrs={'class': 'span8'}),required=True) class Meta: model = User exclude = ('activation_code', 'password_reset_code', 'role') widgets = { 'first_name' : forms.TextInput(attrs= {'type':'text', 'placeholder': "First Name", 'class': 'span8', 'title': 'First Name'}), 'last_name' : forms.TextInput(attrs= {'type':'text', 'placeholder': "Last Name", 'class': 'span8', 'title': 'Last Name'}), 'username' : forms.TextInput(attrs= {'type':'text', 'placeholder': "User Name", 'class': 'span8', 'title': 'User Name'}), 'password' : forms.TextInput(attrs= {'type':'password', 'placeholder': "Password", 'class': 'span8', 'title': 'Password'}), 'email' : forms.TextInput(attrs= {'type': 'text', 'placeholder': "Email Address", 'class': 'span8', 'title': 'Email'}), 'phone' : forms.TextInput(attrs= {'type':'text', 'placeholder': "Phone Number", 'class': 'span8', 'title': 'Start with +88', 'pattern': '^[\+][8][8]\d{11}'}), 'address' : forms.TextInput(attrs= {'type':'text', 'placeholder': "Address", 'class': 'span8', 'title': 'Address'}), 'photo' : forms.FileInput() } views.py def registration(request): form = Registration_Form() if request.method == 'POST': form_values = Registration_Form(request.POST, request.FILES) if form_values.is_valid: form_values.save(commit=False) return … -
Django, Nginx weird behaviour of urls.py
Im developing and API using Django and django-rest-framework. I have a linux server running Ubuntu, there is installed Docker and Nginx, Im running Django App with Postgresql database in docker container. Server's nginx is exposing port 443 and tunneling this to docker via unix socket. Everything seems to be okay. But the part in project-level urls.py is driving me crazy past five hours. My app level urls.py from django.conf.urls import url from devices.viewsets import * from rest_framework.routers import DefaultRouter router = DefaultRouter() router.register(r'endpoint1', Endpoint1ViewSet, base_name='user') router.register(r'users', UsersViewSet, base_name='device') urlpatterns = router.urls Project-level urls.py from django.contrib import admin from django.conf.urls import url from django.urls import include, path from rest_framework.documentation import include_docs_urls API_PREFIX = 'api/v1/' urlpatterns = [ url(API_PREFIX + 'docs/', include_docs_urls(title='NSW Devices API Docs')), url(API_PREFIX + 'admin/', admin.site.urls), url(API_PREFIX, include('devices.urls')) # This line is killing me ] Nginx part: # API location /api/v1 { include uwsgi_params; uwsgi_pass unix:/var/run/api/app.sock; } location /api/v1/static { rewrite /api/v1/static/(.*) /$1 break; root /home/ubuntu/device_api/api/v1/static; } So far I launch the container with docker-compose, and i can acces https://myweb.com/api/v1/docs, https://myweb.com/api/v1/admin but the API endpoints itselfs seems hidden somewhere, because when i try to request https://myweb.com/api/v1/users i get nginx 502 and in docker-compose logs | grep api gives me … -
UnicodeDecodeError while trying to run collectstatic - Using Django
I'm getting a UnicodeDecodeError while trying to push my project to Heroku. I also get this error when I try to run collectstatic in my console. I have no idea what could be causing this. I'm still new, and I can't figure it out by reading through the traceback. I'm using whitenoise to store my static data. If you could help me troubleshoot as to what the problem may be, that would be awesome. Here is the traceback: $ python manage.py collectstatic --noinput remote: Traceback (most recent call last): remote: File "manage.py", line 15, in <module> remote: execute_from_command_line(sys.argv) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line remote: utility.execute() remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 365, in execute remote: self.fetch_command(subcommand).run_from_argv(self.argv) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 288, in run_from_argv remote: self.execute(*args, **cmd_options) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 335, in execute remote: output = self.handle(*args, **options) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 189, in handle remote: collected = self.collect() remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 129, in collect remote: for original_path, processed_path, processed in processor: remote: File "/app/.heroku/python/lib/python3.6/site-packages/whitenoise/storage.py", line 67, in post_process remote: for name, hashed_name, processed in files: remote: File "/app/.heroku/python/lib/python3.6/site-packages/whitenoise/storage.py", line 29, in post_process_with_compression remote: for name, hashed_name, processed in files: remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/staticfiles/storage.py", line 405, in post_process remote: yield … -
Why is the URL not passing information to my view?
I am trying to create a URL that passes information through the URL. from urls.py: url('admin/<int:id>/', views.RequestQueue), from views.py: def RequestQueue(request, id=0): #handle updates to request status if request.method == "POST": request_update = Request.objects.get(pk=id) form = RequestComplete(request.POST, instance=request_update) form.save() pending_requests = Request.objects.filter(status='pending') context = {'pending_requests' : pending_requests, 'status_form' : RequestComplete} template_name = 'pending-queue.html' return render(request, template_name, context) When I run the development server with url like: http://127.0.0.1:8000/requests/admin/10 the page simple 404's -
React Component using codemirror not sending all data on form submission
I am using django, react and react-codemirror2 in my project where a user can input SQL code. I am running into an issue where only part of the text from textarea exists in request.POST. I am finding that mostly just part of the last line of the textarea is sent. I am baffled. React component import React from 'react' import {UnControlled as CodeMirror} from 'react-codemirror2' import DjangoCSRFToken from 'django-react-csrftoken' class SQLForm extends React.Component{ componentDidMount() { let textarea = document.getElementsByTagName('textarea')[0] textarea.setAttribute('name', 'sql'); } render(){ return( <div> <form action="" method="POST"> <DjangoCSRFToken/> <CodeMirror options={{ mode: 'text/x-mssql', theme: 'material', lineNumbers: true }} onChange={(editor, data, value) => { }} /> <br/> <button type="submit">Submit</button> </form> </div> ) } } export default SQLForm super simple django view (just to see what is submitted) def index(request): if 'sql' in request.POST: print(request.POST['sql']) return render(request, 'react.html', {}) else: return render(request, 'react.html', {}) for example, in the text area, if type in the following SELECT * FROM whatever WHERE something=2 print(request.POST['sql']) shows the following at the console =2 And for completeness, this is the textarea that is rendered <textarea autocorrect="off" autocapitalize="off" spellcheck="false" style="position: absolute; bottom: -1em; padding: 0px; width: 1000px; height: 1em; outline: none;" tabindex="0" name="sql"></textarea> -
django models: retrieve foreign key related data as a list inside a response
I have to models: Question and Tags, with "many to many" relations between them. class Tag(models.Model): title = models.CharField(max_length=120) def __str__(self): return self.title class Question(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) tags = models.ManyToManyField(Tag, blank=True) title = models.CharField(max_length=120) text = models.TextField() is_active = models.BooleanField(default=True) creation_date = models.DateTimeField(default=datetime.now) def __str__(self): return self.title class Meta: ordering = ['-creation_date'] When i trying to get questions with associated tags i am getting copies of questions with one tag in it. thats how i try to retrieve questions: list(Question.objects.all().filter(is_active__exact=True).values('id', 'title', 'tags')) i am getting result like this: {'id': 3, 'tags': 1, 'title': 'question 3'}{'id': 3, 'tags': 2, 'title': 'question 3'}{'id': 2, 'tags': 2, 'title': 'question 2'}{'id': 2, 'tags': 3, 'title': 'question 2'}{'id': 1, 'tags': 1, 'title': 'question 1'}{'id': 1, 'tags': 2, 'title': 'question 1'}{'id': 1, 'tags': 3, 'title': 'question 1'} Is there a way to get questions so that all tags associated with it are in the form of a single list. something like this: {'id': 3, 'tags': [1, 2], 'title': 'question 3'}{'id': 2, 'tags': [2, 3], 'title': 'question 2'}{'id': 1, 'tags': [1, 2, 3], 'title': 'question 1'} -
Django REST Framework - How to encrypt the passwords from PUT and PATCH?
Currently any password that I PUT or PATCH do not get encrypted. I am using a ModelSerializer. class UserSerializer (serializers.ModelSerializer): class Meta: model = User fields = ('url', 'username', 'email', 'pk') With a ModelViewSet class UserViewSet (ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer Why are my passwords saved as plain text? And how do I fix this? Should I overwrite the update () in serialiser or update () in ViewSet? Where's the problem? -
Processing command arguments in django
I am trying to add some arguments to my django command. My command will be executing a sql query and I'd like to have an optional argument --first_row and if --first_row is specified the user must specify a second argment --last_row. Here is what I have tried: from django.core.management.base import BaseCommand, CommandError import time class Command(BaseCommand): def add_arguments(self, parser): parser.add_argument('--first_row', nargs='+', type=int) parser.add_argument('--last_row', nargs='+', type=int) def handle(self, *args, **options): import argparse parser = argparse.ArgumentParser() start = time.time() args = parser.parse_args() if args.first_row: print "first row is %d" % (args.first_row) end = time.time() self.stdout.write(self.style.SUCCESS("Operation took %d seconds" % (end-start))) But when I run my command I get this output: manage.py > query_db --first_row 1 usage: manage.py [-h] manage.py: error: unrecognized arguments: query_db --first_row 1 Process finished with exit code 2 What am I doing wrong? -
AJAX GET request successful; View updated but HTML does not get updated
This has completely stumped me and I have stared at the screen for a long time now. It is about a mail app that I am trying to develop. I have an HTML page that is divided in three parts. Left side has the ability to check/uncheck folders from which to view emails. Middle page "should" show all the mails (depending upon what is selected on the left column). The right most column is expanded view of individual mail in the middle. I added AJAX GET request feature to pass to view which folders have been selected or unselected. The view gets the AJAX request all right (in the code below I print out args and it is right what I want it to be). However the HTML page/template never responds to the changing args!! I don't know why? Please help me locate the bug in my program. urls.py from django.conf.urls import url from . import views app_name="Home" urlpatterns = [ url(r'^$', views.Home_View.as_view(),name="Home"), url(r'^RightBody/$', views.RightBody, name="RightBody"), url(r'^RulePopUp/$', views.RulePopUp_View.as_view(), name="RulePopUp"), ] views.py class Home_View(View): def get(self, request): ExcludedFolder = request.GET.getlist('UncheckedFolder[]') LeftSide_FolderHandle = FolderTree("/SomePath/") LeftSide_Folder = LeftSide_FolderHandle.CreateFolderNames() LeftSide_Folder = LeftSide_FolderHandle.MakeAJSONtree() CompleteMailBox_Handle = MailLogger("/SomePath/",FoldersToExclude=ExcludedFolder) CompleteMailBox = CompleteMailBox_Handle.RecreateMailBox() # RightMail = FullMailInTheRight() args = … -
CSRF token error
Friends, I'm new to Django and I need advice. When a user enters his account, he is redirected to the main page of the site (but this is not important), but if he clicks the "Back" button, an authorization page with the old CSRF-token will be displayed. Trying to enter another account will pop up with the error of the CSRF. How to avoid this? -
how to insert records in relational model in relation to the first model(parent-model) database entities
Here, I have two separate models 'User' model and 'Event' model. Event model is related to User mode. Now what i want to do is, when a user fills the event form and submit, then that event record should be created in relation to that user only. views.py class EventCreationForm(View): template_eventcreationform = 'eventcreationform.html' form_class = EventForm def get(self, request): form = self.form_class(None) return render(request, self.template_eventcreationform, {'form': form}) def post(self, request): # data is here form = self.form_class(request.POST) if form.is_valid(): event = form.save(commit=False) user = User.objects.get( ####################################################### ##### currently logged user ##### ### what should i put here to get current user? ### ####################################################### ) form.user = user.email event_name = form.cleaned_data.get('event_name') event_date_time = form.cleaned_data.get('event_date_time') event_address = form.cleaned_data.get('address') event.save() message = 'Event added' return render(request, 'base.html', {'message': message}) else: message = 'Invalid form data, try again' form = self.form_class(None) return render(request, self.template_eventcreationform, {'message': message, 'form': form}) -
Chain Select2 With Django Autocomplete Light Results
I am initializing two Select2s like this: $("#id_category").select2({ dropdownParent: $('.modal-body'), ajax: { url: "/aca/", dataType: 'json', type: "get", } }); $("#id_item").select2({ dropdownParent: $('.modal-body'), ajax: { url: "/aa/", dataType: 'json', type: "get", } }); The URLs for the ajax data are defined by this Python code using django-autocomplete-light: class CategoryAutocomplete(autocomplete.Select2QuerySetView): def get_queryset(self): qs = Category.objects.all() if self.q: qs = qs.filter(category__icontains=self.q) return qs class ItemAutocomplete(autocomplete.Select2QuerySetView): def get_queryset(self): qs = Item.objects.all() category = self.forwarded.get('category', None) if category: qs = qs.filter(category=category) if self.q: qs = qs.filter(item__icontains=self.q) return qs The Select2s implemented in JavaScript are not picking up the forwarding changes defined by the autocomplete views because the Select2s are both initialized prior to a choice being made. Even when I initialize the second Select2 after the first changes, chaining still doesn't occur. Why is this? -
How can I filter a model in django based on a field of a many to many related object?
I have two models related to each other with a many to many. I want to filter for one, Message, based on a field on the other, User.created_at, compared to a field on the first, Message.edit_date. class Message(Model): content = CharField(max_length=512, blank=True, null=True) created_at = models.DateTimeField(blank=True, null=True) edit_date = models.DateTimeField(blank=True, null=True) users = models.ManyToManyField('User', related_name='message_user') class User(Model): name = content = CharField(max_length=48) created_at = models.DateTimeField(blank=True, null=True) Right now I am achieving this by looping over the two models and comparing them in the loop, which is slow. message_query = Message.objects.none() for user_name, created_at_date in Users.objects.filter(name='Tina').values_list('id', 'created_at').iterator(): message_query.add(Q( users=user_id, edit_date__gte=created_at_date, ), Q.OR) messages = Message.objects.filter(message_query) Is there any way to create a filter for the items I'm attempting to filter for in a query? -
How to get livereload to work with django
So I've got a Django/Vue project I'm trying to get off the ground. It's currently being pretty inconsistent. (I was able to get Vue to generate some things, but not others) I've followed these instructions pretty much to the letter: https://github.com/tjwalch/django-livereload-server Although it is unclear how the three options apply to ./manage.py runserver (runserver and livereload seem like mutually exclusive arguments for manage.py) Despite the browser indicating GET http://127.0.0.1:32657/livereload.js net::ERR_CONNECTIONREFUSED I was still getting it to work but it was inconsistent. Something simple: <html> <head> <script src="https://unpkg.com/vue/dist/vue.js"></script> <body> <div id="app"> <p>{{ title }}</p> </div> <script> new Vue({ el: '#app', data: { title: 'yadda yadda' } }); </body> </html> And nothing on the screen. I'm not entirely sure livereload is the issue, but it would be nice to set it up properly. When I updated the settings file to include the hostname and port, it changed to this: GET http://darkseid:8000/livereload.js net::ERR_ABORTED and Not Found: /livereload.js [30/Mar/2018 16:42:57] "GET /livereload.js HTTP/1.1" 404 2506 So find yields that livereload is indeed there. ./home/jason/env/lib/python2.7/site-packages/livereload-2.5.1.dist-info ./home/jason/env/lib/python2.7/site-packages/livereload ./home/jason/env/lib/python2.7/site-packages/livereload/vendors/livereload.js ./home/jason/env/lib/python2.7/site-packages/livereload/management/commands/livereload.pyc ./home/jason/env/lib/python2.7/site-packages/livereload/management/commands/livereload.py ./home/jason/env/bin/livereload Im tempted to just copy the .js file to the static directory that I have livereload watch. Is that right? Any help would be appreciated! -
Why can't I authenticate a Django user created from a custom manage.py command?
This one has me completely stumped. I have a model which extends the base User model in Django, so I am writing a custom manage.py command to create superusers. It seems to be working fine, but for some reason any users that I create via this custom command cannot be authenticated by Django. When I check the database, the users are indeed being created and all of the information is correct. Here's the code for my custom command in a file called createadmin.py (I've omitted the bits of code irrelevant to the problem): from django.core.management.base import BaseCommand, CommandError from django.contrib.auth.models import User class Command(BaseCommand): help = 'Creates a Django admin user' def handle(self, *args, **options): username = raw_input('Admin username: ') password = raw_input('Admin password: ') try: new_user = User.objects.create_user(username, password, '') new_user.is_superuser = True new_user.is_staff = True new_user.save() self.stdout.write('Admin created successfully') except: self.stdout.write('Sorry, there was a problem creating a new user in the database.') Now, if I run this command using python manage.py createadmin, everything seems to work and the user is created in the database. To demonstrate the problem, here is the output from testing with createadmin and shell: createadmin Admin username: testadmin Admin password: admin Admin created successfully … -
django-rest-framework login via Ajax returns HTML
I'm using the django-rest-framework and trying to login using Ajax, but the login API is returning HTML instead of JSON. My configs: REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_jwt.authentication.JSONWebTokenAuthentication', 'rest_framework.authentication.SessionAuthentication', ), 'DEFAULT_RENDERER_CLASSES': ( 'rest_framework.renderers.JSONRenderer', 'rest_framework.renderers.BrowsableAPIRenderer', ) } And the Ajax call: $.ajax({ url: '/api-auth/login/', method: 'POST', data: "username=xxxxx&password=123", headers: { Accept: 'application/json' }, success: function(resp) { console.log(resp); }, error: function(resp) { console.error(resp); } }); Even if I'm specifying the Accept header, it always returns text/html. Am I using the wrong endpoint? I'm using JSONWebToken for external clients (ie, mobile) and the SessionAuthentication for same domain web requests. I expect the SessionAuthentication to set the cookie I can use to make further requests once logged in. If the login fails, I expect the API to return the error in JSON (ie, "Invalid username and password"). Using: Django==1.11 djangorestframework==3.7.7 djangorestframework-jwt==1.11.0 -
Heroku Automatic Certificate Management - Domains Failing Validation
I'm trying to use the new Heroku Automated Certificate Management. when i run heroku certs:auto I get the following error: Some domains are failing validation, please verify that your DNS matches: heroku domains I can't figure out what the problem is and have followed this document from Heroku https://devcenter.heroku.com/articles/automated-certificate-management#troubleshooting I have my DNS on godaddy setup as follows: and when i run heroku domains i get this Anyone have any ideas? -
Django joining two tables
So here is my two models Offre and Recruteur: @python_2_unicode_compatible class Recruteur(models.Model): name = models.CharField(max_length=50) def __str__(self): return "Recruteur: {}".format(self.name) @python_2_unicode_compatible class Offre(models.Model): title = models.CharField(max_length=100, default=0) idRecruteur = models.ForeignKey(Recruteur, on_delete=models.CASCADE) def __str__(self): return "Offre: {}".format(self.title) I want to output the name of the Recruteur for every idRecruteur of the table Offre -
Prevent jQuery Select2 from Loading All AJAX Data of Django Autocomplete Light View
I have a django-autocomplete-light view that takes a larger model named Entity (20,000 records) and filters it down to 10-12 records based on a bit field named members: class MembersAutocomplete(autocomplete.Select2QuerySetView): def get_queryset(self): qs = Entity.objects.filter(members=1) if self.q: qs = qs.filter(Q(entity__istartswith=self.q) | Q(entityType__istartswith=self.q) | Q(entityDescription__icontains=self.q)) return qs.order_by('entityType', 'entity') I then initialize my Select2 with JavaScript to avoid a Firefox issue of not focusing on a Select2 in a modal: $("#id_assignedTo").select2({ dropdownParent: $('.modal-body'), placeholder: "", minimumInputLength: 2, ajax: { url: "/project/membersautocomplete/", dataType: 'json', type: "get", } }); When I load my modal, the performance of my site takes a massive hit because the Select2 is initialized with all of the records from Entity, not the filtered view mapped to /project/membersautocomplete/. When I navigate to /project/membersautocomplete/, I see the expected 10-12 records in JSON format. Two Questions: How is Select2 even seeing the underlying model/table when it's pointed to a URL that only includes a small amount of data? Is it possible to prevent Select2 from loading any options prior to clicking on the dropdown and selecting an option? -
Django: How to send a GET request to an external server and print response?
This is the code I wrote to send GET request. On my Node js server I am able to log the incoming request when I send request from Django, and in the browser if I enter the Node js url I get the output text in the browser. But I am unable to show the response in Django. data = {'query': 'Test'} r = requests.get('http://localhost:8080/?', params=data) how do I print the data returned by http://localhost:8000 ? -
How to handle users and roles by app in Django
Hello everyone let me ask something about the admin interface and how can I handle my users by app. Well so sorry I'm nooby first of all. So, I need to create a new app for basically take some quiz so I will need users and these users within my app should have a different role as a student or teacher and so on. The thing is that I don't know if the admin Django interface is just for the DB models or whether I can use it as a security layer in my app. Or otherwise, I should create a buck of tables in my app model for users and roles and then handle everything from the model because the admin is just the DB access. what could you tell me? thanks so much. -
Set dropdownParent of Existing Select2
I have a Select2 that is a autocomplete widget from Django. Due to a known issue with Firefox not focusing on the Select2 when inside a modal, I use this line to add the dropdownParent: $("#id_project").select2({dropdownParent: $(".modal-body")}); This causes the initial definition of the Select2 (including the data url) to be lost. How do I set the dropdownParent of an existing Select2? Current JS code to load my modal: var loadForm = function () { var btn = $(this); $.ajax({ url: btn.attr("data-url"), type: 'get', dataType: 'json', beforeSend: function () { $("#modal-task").modal("show"); }, success: function (data) { $("#modal-task .modal-content").html(data.html_form); //$("#id_project").select2({dropdownParent: $(".modal-body")}); $('#id_targetDate').datepicker({ minDate: 0 }); $('#id_completedDate').datepicker({ maxDate: new Date}); } }); }; -
Setting dropdownParent for django-autocomplete-light Select2
I have a django-autocomplete-light widget in forms.py: 'project': ModelSelect2(url='projectautocomplete',), Select2 has a known issue in Firefox of not focusing when inside a modal...so this is necessary in JavaScript: $("#id_project").select2({dropdownParent: $(".modal-body")}); This causes the previous widget definition to be invalid, so the Select2 does not connect to the autocomplete data. Is it possible to tell a django-autocomplete-light widget to focus on .modal-body? -
Can I use Mozilla Pontoon to automatically detect Angular 5 strings
I was searching for a translation tool for my angular app and while bench marking the different available open-source solutions, I found the Mozilla translation tool called Pontoon: https://pontoon.mozilla.org/ The project seems very attractive, so I installed the docker version, In the root README on github, they say that Pontoon automatically detects localization strings, and I can't figure out how they do this, and if I can plug this awesome translation tool to my Angular 5 project ? -
Boostrap modal not picking up correct Django values
I am just wondering why this modal isn't picking up the correct values. When I click on the button it will only display one dog's additional information. I read somewhere it maybe due to some id thing but can't figure it out. Below is a snippet of code. {% for breed in breeds %} <tr> <td>{{ breed.name }}</td> <td><a href="{{ breed.url }}" target="_blank"><img src="{{ breed.image.url }}" alt="image"></a></td> <td>{{ breed.get_activity_level_display }}</td> <td>{{ breed.get_coat_length_display }}</td> <td>{{ breed.get_drools_display }}</td> <td>{{ breed.get_good_with_children_display }}</td> <td>{{ breed.get_grooming_demand_display }}</td> <td>{{ breed.get_intelligence_display }}</td> <td>{{ breed.get_shedding_level_display }}</td> <td>{{ breed.get_size_display }}</td> <td><button type="button" class="btn btn-primary" data-toggle="modal" data-target="#breedModal">Click Here</button></td> </tr> <div class="modal fade" id="breedModal" tabindex="-1" role="dialog" aria-labelledby="breedModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title preferences" id="breedModalLabel">Additional Information - {{ breed.name }}</h5> </div> <div class="modal-body preferences"> Group: {{ breed.group }}<br> Height: {{ breed.height }}<br> Weight: {{ breed.weight }}<br> Life Span: {{ breed.life_span }}<br> </div> <div class="modal-footer"> <button type="button" class="btn btn-primary" data-dismiss="modal">Close</button> </div> </div> </div> </div> {% endfor %}