Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
DJANGO 2.0 Can I replace a ForeignKey and add PositiveIntegerField to store the pk only
I want to replace the user ForeignKey by a PositiveIntegerField is it permitted? models.py from: from_user = models.ForeignKey(settings.AUTH_USER_MODEL,related_name = 'sender_%(class)s' ,on_delete = models.CASCADE) to: from_user = models.PositiveIntegerField(editable = False) -
Speech to text/Audio input in django
import speech_recognition as sr def speechToText(): r = sr.Recognizer() with sr.Microphone() as source: r.adjust_for_ambient_noise(source) print("Say something") audio = r.listen(source) try: print("You said\n" + r.recognize_google(audio)) except Exception as e: print(e) I have the following script to take input from mic and convert it to text using the API. Although, I am unable to figure out how to hook this code up with a template in Django. Plox help. -
django rest framework oauth2 access token is not valid
I have a login endpoint using oauth2 outhentication in django,it returns me access token but when I copy that token it returns me token is not valid -
keep getting an error on there is no module
In my Django project while I have made an app named employee. And have registered it in my apps but I keep getting this error: No module named 'employee' And the app can't run. please inform me. thanks, -
JsonResponse is been read as string during django_nose testing
having a head ache here. I have this simple API that I want to test out but can't so far. It works partly. The error happens if the user is blocked or deleted, which says: 'str' object has no attribute status_code. But I think I am indeed responding with a JsonResponse in all cases. Worse yet, it works correctly for correct user and when the email doesn't exist. And when checking from postman, it responds correctly with status 400 and correct message. Am I missing something with my tests? class ForgotPwd(APIView): permission_classes = [] def post(self,request, format = None): email = request.data.get('email' , '').strip() reply = {} status = 400 filters = {} if email: filters['email'] = email try: user_info = User.objects.values('id', 'status', 'email').get(**filters) if user_info['status'] == 0: reply['detail'] = _('userBlocked') elif user_info['status'] == 2: reply['detail'] = _('userMissing') else: # send email reply['detail'] = _('pwdResetLinkSent') status = 200 except BaseException as e: reply['detail'] = _('errorNoAccount') else: reply['detail'] = _('errorNoAccount') return JsonResponse(reply,status=status) My test: class ForgotPwdTest(APITestCase): """ Test module for initiating forgot password """ def setUp(self): self.valid_payload = { 'email': 'valid@gmail.com' } self.invalid_email_payload = { 'email': 'invalid@yahoo.com' } self.blocked_user_payload = { 'email': 'blocked@gmail.com' } self.deleted_user_payload = { 'email': 'deleted@gmail.com' } user_valid … -
Do sessions in Django expire without a request?
This answer suggests that it's possible to attach to "on session end" event in Django. However, this event seems to be called only when Django deletes the session from the database (please, correct me if I'm wrong). Does this happen only upon a request from the browser that has this session's cookie, or is there a background thread in Django that deletes sessions from the DB when they expire and calls "on sessssion end" event (more precisely, issues pre_delete signal)? Some context: I'm writing an application that allocates some resources when the session is created. And I need to deallocate these resources when the session expires. -
django email: sender appears as receiver in my inbox
I'm sending emails from my page, and they go through the pipe just fine, content and title appearing in the email. However, in my email inbox they appear as being sent by EMAIL_HOST_USER rather than 'sender' which is problematic, of course. I've tried changing form.cleaned_data['sender'] to form.cleaned_data.get('sender') but to no avail. Does anyone know what the problem is here? FORM: class ContactForm(forms.Form): title = forms.CharField(label='title', max_length=100, required=True) content = forms.CharField(label='content', widget=forms.Textarea, required=True) sender = forms.EmailField(label='sender', required=True) VIEW: def contact(request): if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): subject, from_email, to = form.cleaned_data['title'], form.cleaned_data['sender'], os.environ.get('EMAIL_HOST_USER') text_content = form.cleaned_data['content'] html_content = '<p>Hey, <b>vulpes!</b> Some unfortunate soul sent you this message a little while ago:</p><p>{0}</p>'.format(form.cleaned_data['content']) msg = EmailMultiAlternatives(subject, text_content, from_email, [to]) msg.attach_alternative(html_content, "text/html") msg.send() messages.info(request, f'your message has been sent.') return redirect('vault:about') else: form = ContactForm() return render(request, 'vault/about.html', {'form':form}) -
I am trying to autopopulate a form's field using a user's previous input. Using AJAX and Django without refreshing the page
I am an amateur Django developer and I'm creating a student's portal as a project. I am having a slight problem as to how a student can select his units based on his previous form field inputs. I have searched everywhere on how to do it, but the closest I've found is an example in W3Schools website; here it is. I would like to implement a similar structure in my project but I don't know how to do it in my template. Here are the files models.py from django.db import models class UnitReg(models.Model): YOS=( ('First Year','First Year'), ('Second Year','Second Year'), ('Third Year','Third Year'), ('Fourth Year','Fourth Year') ) SS=( ('2017/2018','2017/2018'), ('2018/2019','2018/2019') ) UNITS = ( ('Algorithms','Algorithms'), ('Artificial Intelligence','Artificial Intelligence'), ('OOP','OOP') ) year_of_study = models.CharField(max_length=30, choices=YOS) selected_semester = models.CharField(max_length=30, choices=SS) selected_units = models.Charfield(max_length=30, choices=UNITS) forms.py from django import forms from .models import UnitReg class UnitRegForm(forms.ModelForm): class Meta: model = UnitReg fields = ['year_of_study', 'selected_semester'] views.py from django.shortcuts import redirect, render from .forms import UnitRegForm from django.contrib import messages from django.contrib.auth.decorators import login_required @login_required def unitregister(request): if request.method == 'POST': form = UnitRegForm(request.POST) if form.is_valid(): form.save() messages.success(request, f'Your unit registration was successful') return redirect('profile') else: form = UnitRegForm() context = { 'form':form } … -
I can't create new project with bitnami django on Linux
i just install Django Stack 2.1.5-0, and i want to create new project with this command: sudo django-admin.py startproject coba but the terminal give me result: bash: django-admin command not found and i want to create it in here: opt>djangostack>apps do i need to install python3 and django first event though i have use django stack? please help me :) -
How to get individual form data inside a form array
So i have a form array and passing it to the html and it worked. But i have a problem getting the data. How to get the data from a form array? forms.py: class ItemStockChangeForm(forms.Form): name = '' stock = 0 choices = [('add', 'Add'), ('sub', 'Sub')] action = forms.ChoiceField(choices=choices) qty = forms.IntegerField(min_value=0, initial=0, required=False) desc = forms.CharField(widget=forms.TextInput(), required=False) view.py: product = Product.objects.get(id=p_id) items = product.item_set.all() forms = [] for item in items: tmp = ItemStockChangeForm() tmp.name = item.name tmp.stock = item.stock forms.append(tmp) if request.method == 'POST': for form in forms: form = ItemStockChangeForm(request.POST) print (form.data['qty']) context = { 'forms':forms } return render(request, 'Warehouse/test.html', context) test.html: {% extends "Gudang/base.html" %} {% block contentbody %} <form method="POST"> <table class='table-stock'> {% csrf_token %} {% for form in forms %} {% if forloop.first %} <thead> <tr> <th> Name </th> <th> Stock </th> {% for f in form %} <th> {{ f.label }} </th> {% endfor %} </tr> </thead> {% endif %} <tbody> <tr> <td> {{ form.name }} </td> <td> {{ form.stock }} </td> {% for f in form %} <td> {{ f }} </td> {% endfor %} </tr> </tbody> {% endfor %} </table> <button type='submit'>Save</button> </form> {% endblock contentbody %} I tried using … -
tuple index out of range - Rate limited Django view
im currently filtering my django views with django-ratelimit==2.0.0 but for some reason i get the following error at my post_edit view: tuple index out of range this is the one and only view where this behavior appears: @ratelimit(key='header:Cookie', rate='10/m', block=True) def post_edit(request, pk): post = get_object_or_404(Post, pk=pk) if request.user == post.author: if request.method == "POST": form = PostForm(request.POST, request.FILES, instance=post) if form.is_valid(): post = form.save(commit=False) post.published_date = timezone.now() post.save() return redirect('post_detail', pk=post.pk) else: form = PostForm(instance=post) return render(request, 'myproject/post_edit.html', {'form': form}) else: messages.success(request, 'Uups, something went wrong, please try again or contact the support') return redirect('post_detail', pk=post.pk) The funny fact is that i use almost the same view or function at the user dashboard and it's working fine?! @ratelimit(key='header:Cookie', rate='10/m', block=True) def post_edit_from_home(request, pk): post = get_object_or_404(Post, pk=pk) if request.user == post.author: if request.method == "POST": form = PostForm(request.POST, request.FILES, instance=post) if form.is_valid(): post = form.save(commit=False) post.published_date = timezone.now() post.save() messages.success(request, 'You have successfully changed the Post') return redirect('home') else: form = PostForm(instance=post) return render(request, 'myproject/_from_home/post_edit_from_home.html', {'form': form}) else: messages.success(request, 'Uups, something went wrong, please try again or contact the support') return redirect('home') according to the console error i get the following: File "/myproject/venv/lib/python3.6/site-packages/ratelimit/decorators.py", line 20, in _wrapped if isinstance(args[0], … -
Django model for voting system and follow feature
I work on the voting system (vote up and vote down) and the functionality - follow. I want it to be done well, because I don't have anyone to advise, I put the post and code here. Follow function - it should show how many followers there are and who they are. I used here a m2m relation with the intermediate model Follower. My question - is this the correct approach to the topic - using m2m with an intermediate model here? Functionality vote up and vote down - it is supposed to show how many votes up and how many down and who voted down and who voted up. My question is whether there is also OK here with the relation between m2m and the intermediate model Voter? Code for follow feature: class Post(models.Model): owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='posts') title = models.CharField(max_length=255, unique=True) description = models.TextField(max_length=1024) followers = models.ManyToManyField(settings.AUTH_USER_MODEL, through='Follower', blank=True) is_visible = models.BooleanField(default=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) def __str__(self): return self.title def get_absolute_url(self): return reverse('posts:post_detail', kwargs={'pk': self.pk}) def number_of_followers(self): return self.followers.count() class Follower(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) def __str__(self): return self.user Code for vote up and … -
django rest framework - session auth vs token auth, csrf
I have DRF set with the default settings. My ajax clients works fine with the session authentication. I want another remote server to consume the same API as the javascript clients. My login code is simple: class Login(APIView): def post(self, request, *args, **kwargs): user = authenticate(username=username, password=password) if user is None: # Incorrect credentials return Response(status=status.HTTP_401_UNAUTHORIZED) login(request, user) # ... The issue is when I use a client from another host, like python requests, I get CSRF error. According to DRF docs, I think I should use a token auth instead. Question: Why I can't use the same session based auth for both javascript and software clients? After all, the session itself is also a token stored in a cookies, so using requests with: session = requests.session() session.post('/login/', data={'username': '', 'password': ''}) Should save the cookie and work just fine. The only problem is the CSRF. I prefer using session auth, and not to create another table for token based auth (I see no point in that). -
Scheduling Django method with Celery
I have this method: def getExchangeRates(): """ Here we have the function that will retrieve the latest rates from fixer.io """ rates = {} response = urlopen('http://data.fixer.io/api/latest?access_key=c2f5070ad78b0748111281f6475c0bdd') data = response.read() rdata = json.loads(data.decode(), parse_float=float) rates_from_rdata = rdata.get('rates', {}) for rate_symbol in ['USD', 'GBP', 'HKD', 'AUD', 'JPY', 'SEK', 'NOK']: try: rates[rate_symbol] = rates_from_rdata[rate_symbol] except KeyError: logging.warning('rate for {} not found in rdata'.format(rate_symbol)) pass return rates @require_http_methods(['GET', 'POST']) def index(request): rates = getExchangeRates() fixerio_rates = [Fixerio_rates(currency=currency, rate=rate) for currency, rate in rates.items()] Fixerio_rates.objects.bulk_create(fixerio_rates) return render(request, 'index.html') I want to schedule this, let's say, for every day at 9am, except for weekends. I haven't found some comprehensive tutorial on how to schedule this based on such a specific datetime, also, I don't know if I could schedule this method, or create another method in my tasks file that inherits this one, and runs at any specific date. I do have the celery.py file in my project root, and the tasks.py file in my app folder. Or, maybe celery isn't the way to go for this situation? Any ideas? -
How to use Django Formsets with different labels?
How to create Different labels for my Django Formsets? I have input fields on my html page created with forms Charfield, and every time the amount of my input fields are different based on my list. I want each time showing my inputs to have different labels or titles? edit_files.html { % block content %} <form action="." method="POST">{% csrf_token %} {{ form.management_form }} {% for each_f in form %} <br/>{{ each_f.as_p }} {{ 1|add:1}} {% endfor %} <input type="submit" value="Save" name="lines" /> </form> {% endblock %} forms.py from django import forms from .models import DocFile class DocumentForm(forms.ModelForm): class Meta: model = DocFile fields = ('description','document') class RawProductionForm(forms.Form): title_forms = forms.CharField(label='') views.py def edit_files(request, file_id): instance = get_object_or_404(DocFile, id=file_id) # finding variables in the doc exact_file = Document(instance.document) variables = [] for paragraph in exact_file.paragraphs: match = re.findall(r"\{(.*?)\}", paragraph.text) variables.append(match) for table in exact_file.tables: for row in table.rows: for cell in row.cells: match = re.findall(r"\{(.*?)\}", cell.text) variables.append(match) exact_file.save('green.pdf') temporary_list = [] # as with a Paragraph code we get lists of list , and have multiple little lists we get rid of empty lists for i in variables: for j in i : if len(j) > 0: temporary_list.append(j) variables = temporary_list … -
I have valid a View in my views.py file but still giving me error 'not a valid view function'
I am using Django 2.1 ` from django.shortcuts import render,redirect,get_object_or_404 from .forms import PostUrl from .models import UrlLink def total_url(request): urls=UrlLink.objects.all() return render(request,'core/shorturl.html',{'urls':urls}) def url_list(request,pk): url = get_object_or_404(UrlLink,pk=pk) return render(request,'core/url_detail.html',{'url':url}) def url_new(request): if request.method == "POST": form=PostUrl(request.POST) if form.is_valid(): url=form.save() return redirect('total_url') else: form=PostUrl() return render(request,'core/url_list.html',{'form':form}) ` but when I submit the form I am getting the error NoReverseMatch at / Reverse for 'total_url' not found. 'total_url' is not a valid view function or pattern name. -
Django Fetch column from foreign key table
I am new on Django. I have trouble fetching column from the foreign key table. The task at hand is to create a CSV with some columns from two tables(table 1, table 2). I have created two models as : class SomeDetails(models.Model): type = models.IntegerField() class Meta: db_table = 'table2' class Report(models.Model): transfer_platform = models.CharField(verbose_name="Transfer platform", max_length=255) status = models.IntegerField(verbose_name="Status(4=success, 5=failed)") amount = models.DecimalField(decimal_places=2, max_digits=20) created_at = models.DateTimeField() some_uuid = models.ForeignKey('SomeDetails', on_delete=models.CASCADE) class Meta: db_table = 'table1' csv code: qs = Report.objects.filter(created_at__gte=datetime.today().date() + timedelta(-1)).filter( status=4).values('id', 'transfer_platform', 'status', 'amount', 'created_at', 'some_uuid__type') The above doesnt return any data apart from the column headers. But if i remove the 'beneficiary_uuid__type' from above query it returns the correct data. I have also tried prefetch_related, but somehow havent been able to work it out. Please help me get all the five columns so that i can populate it in the csv. Python version : 2.7 -
DRF routing models with same name in
I'm setting up a DRF API which has multiple apps with the same model names. How should I configure the router to find the correct model? The project has two apps, 'GreenApp' and 'BlueApp' both of which have a Client model that has a OneToOne relationship with the User. Green App green_app.models.profiles.py from users.models import User class Client(models.Model): user = models.OneToOneField(User, related_name="green_client") ... green_app.serializers.profiles.py from rest_framework import serializers from green_app.models.profiles import Client class GreenClientSerializer(serializers.HyperlinkedModelSerializer) class Meta: model = Client fields = ('url, 'user', ...) green_app.viewsets.profiles.py from rest_framework import viewsets from green_app.models.profiles import Client class GreenClientViewset(viewsets.ModelViewSet): queryset = Client.objects.all() serializer_class = GreenClientSerializer Blue App blue_app.models.profiles.py from users.models import User class Client(models.Model): user = models.OneToOneField(User, related_name="blue_client") ... blue_app.serializers.profiles.py from rest_framework import serializers from green_app.models.profiles import Client class BlueClientSerializer(serializers.HyperlinkedModelSerializer) class Meta: model = Client fields = ('url, 'user', ...) blue_app.viewsets.profiles.py from rest_framework import viewsets from blue_app.models.profiles import Client class BlueClientViewset(viewsets.ModelViewSet): queryset = Client.objects.all() serializer_class = BlueClientSerializer users.serializers.py from rest_framework import serializers from green_app.serializers.profiles import GreenClientSerializer from blue_app.serializers.profiles import BlueClientSerializer from users.models import User class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = ('url', 'green_client', 'blue_client') users.viewsets.py from rest_framework import viewsets, permissions from users.models import User class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer … -
How to send non field data to django template form from view's def post in Createview?
Here i am saving customer with billing address and shipping address. so customer as one table and address as another table. customer table has foreign key relation for billing address and shipping address. i am not able to use inline formset because customer table needs two address columns. and its saving everything is fine but when form errors came address data is not sending to form back. address will be empty in template. so i thought to send those address data to template with form any one please give solution to resolve this problem. def post(self,request): if form.is_valid(): BillingAddress=convertToNull(request.POST.get('billing_address')) Billing_City=convertToNull(request.POST.get('billing_city')) Current_Billing_Address=Address.objects.create(address=BillingAddress,city_id=Billing_City) ShippingAddress=convertToNull(request.POST.get('shipping_address')) Shipping_City=convertToNull(request.POST.get('shipping_city')) Current_Shipping_Address=Address.objects.create(address=ShippingAddress,city_id=Shipping_City) Customer.objects.filter(pk=CustomerModel.pk).update(shipping_address_id=Current_Shipping_Address.pk,billing_address_id=Current_Billing_Address.pk) else: context={'BillingAddress':BillingAddress} return render(self.request,self.template_name,{'form':form},context) -
Show resulting JSON from API in simple Django template
I have this method: def getExchangeRates(): """ Here we have the function that will retrieve the latest rates from fixer.io """ rates = {} response = urlopen('http://data.fixer.io/api/latest?access_key=c2f5070ad78b0748111281f6475c0bdd') data = response.read() rdata = json.loads(data.decode(), parse_float=float) rates_from_rdata = rdata.get('rates', {}) for rate_symbol in ['USD', 'GBP', 'HKD', 'AUD', 'JPY', 'SEK', 'NOK']: try: rates[rate_symbol] = rates_from_rdata[rate_symbol] except KeyError: logging.warning('rate for {} not found in rdata'.format(rate_symbol)) pass return rates @require_http_methods(['GET', 'POST']) def index(request): rates = getExchangeRates() fixerio_rates = [Fixerio_rates(currency=currency, rate=rate) for currency, rate in rates.items()] Fixerio_rates.objects.bulk_create(fixerio_rates) return render(request, 'index.html') The API I'm calling has a resulting json like this: "rates": {"SAR": 4.394498, "INR": 49.836962, and so on... How can I sort of "template" that result, in just an easy way, I've tried something like this: <ul> {% for obj in objects %} <li>{{ obj.currency }} - {{ obj.rate}}</li> {% endfor %} </ul> But obvisouly it's just a blank page. Any ideas? I just wanna show the list of currency and respective rates, no fancy stuff. -
Django: {{}} in href
How to use {{ }} in a ''? <!-- css --> {% if user.theme %} <link href="{% static 'bulmaswatch/{{ user.theme }}/bulmaswatch.min.css' %}" rel="stylesheet"> When I use this,The static file css will not load up.How to make {{ user.theme }} a variable instead of a text? -
What is wrong with this? ['ManagementForm-Daten fehlen oder wurden manipuliert.']
I get this error: ['ManagementForm-Daten fehlen oder wurden manipuliert.'] This is my model: from django.db import models from daytrips.models import Trip class Buchungen(models.Model): PERSONEN_CHOICES = [(i, str(i)) for i in range(1,10)] reiseziel = models.CharField(max_length=50) datum_abfahrt = models.CharField(max_length=50) vorname = models.CharField(max_length=50) nachname = models.CharField(max_length=50) adresse = models.CharField(max_length=50) plz = models.CharField(max_length=20) stadt = models.CharField(max_length=50) email = models.EmailField() telefon = models.CharField(max_length=50) geburtsdatum = models.CharField(max_length=200) personen = models.IntegerField( choices=PERSONEN_CHOICES, default=0) preis = models.DecimalField(default=0.00, max_digits=100, decimal_places=2) gesamt = models.DecimalField(default=0.00, max_digits=100, decimal_places=2) created = models.DateTimeField(auto_now_add=True) updated = models.DateField(auto_now=True) class Meta: ordering = ('-created',) verbose_name = 'Buchung' verbose_name_plural = 'Buchungen' def __str__(self): return self.vorname def save(self, *args, **kwargs): self.gesamt = self.preis * self.personen super(Buchungen, self).save(*args, **kwargs,) class Mitreisende(models.Model): buchung = models.ForeignKey(Buchungen, related_name='items', on_delete=models.CASCADE) reiseziel = models.ForeignKey(Trip, related_name='order_items', on_delete=models.CASCADE) vorname = models.CharField(max_length=50) nachname = models.CharField(max_length=50) geburtsdatum = models.CharField(max_length=200) In my forms.py i have: from django import forms from django.forms import HiddenInput from django.forms import modelformset_factory from .models import Buchungen, Mitreisende class BuchungForm(forms.ModelForm): class Meta: model = Buchungen fields = [ 'reiseziel', 'datum_abfahrt', 'vorname', 'nachname', 'adresse', 'plz', 'stadt', 'email', 'telefon', 'geburtsdatum', 'preis', 'personen', 'gesamt', ] widgets = { 'personen': forms.Select, } reiseziel = forms.CharField(widget=forms.TextInput(attrs={'reiseziel': 'reiseziel', 'readonly': 'readonly'})) datum_abfahrt = forms.CharField(widget=forms.TextInput(attrs={'datum_abfahrt': 'datum_abfahrt', 'readonly': 'readonly'})) MitreisendeModelFormset = modelformset_factory( Mitreisende, fields = … -
why django development server act like single thread while the docs "The server is multithreaded by default."-- version 2.1
I am a beginner of Django web framework, and I'm using Django 2.1.2. Now I encountered one question, does Django run in single thread or multithreads ?I checked the docs and it says 'the server is multithreaded by default.' while i have tested in my local env, it act just like single-thread. my view functions is: class Hello(APIView): """ for testing django single-threading """ def get(self, request): print("enter in the view") time.sleep(10) print("finished...") return HttpResponse("finished!") I run Django application in terminal by: python manage.py runserver I requested the url twice at nearly the same time, and the reponse is: enter in the view finished... [13/Jan/2019 10:43:50] "GET /account/hello HTTP/1.1" 200 9 enter in the view finished... [13/Jan/2019 10:44:00] "GET /account/hello HTTP/1.1" 200 9 It handled requests just like in single-thread way, did I do something wrong or I understand in wrong, thanks for help. -
add a png image to an existing pdf in django
I am trying to add a .png file in an existing pdf. I got an example,i edited the position of .png in pdf to place it in left-bottom corner. But it is creating new pdf. I tried to go through reportlab's documentation to get any hits but failed. What should i do to achieve the desired result? I want to achieve it though any 3rd party python package or related to python code not using photoshp or adobe acrobat. def PrintImage(request): response = HttpResponse(content_type='application/pdf') doc = SimpleDocTemplate(response,rightMargin=600, leftMargin=0, topMargin=150, bottomMargin=18) doc.pagesize = landscape(A4) elements = [] I = Image('static/images/account.png') I.drawHeight = 1.0*inch I.drawWidth = 1.0*inch elements.append(I) doc.build(elements) return response -
How can I access certain table rows in a for loop?
I wan't to highlight only the contacts of a company they're related to in my table body. At the moment I'm only able to highlight all of the contacts regardless of which company's contacts they are. I don't think I can use find() method since the contact row is different from he company row. tbody {% for company in company_list %} <tr class="company-row"> <th class="company-name" scope="row">{{ company.name }}</th> <td>{{ company.order_count }}</td> <td class="order-sum">{{ company.order_sum|floatformat:2 }}</td> <td class="text-center"><input type="checkbox" name="select{{company.pk}}" id=""></td> </tr> {% for contact in company.contacts.all %} <tr class="contact-row"> <td>{{ contact.first_name }} {{ contact.last_name }}</td> <td class="contact-orders">Orders: {{ contact.order_count }}</td> <th>&nbsp;</th> <td></td> </tr> {% endfor %} {% endfor %} script $(document).ready(function() { $(".company-row").hover(function() { sum = $(this).find(".order-sum").html() // get value of total sales if (sum > 50000) { $(this).addClass("company-row-over") // green $(".contact-row").each(function() { orders = $(this).find(".contact-orders").html() // get orders from each contact orders = orders.split(':') orders = orders[1] orders = parseInt(orders) if (orders > 3) { $(this).addClass("contacts") // yellow } }) } else { $(this).addClass("company-row-under") // orange } }, // clear highlighting on mouse out function() { $(this).removeClass() $("table tr#contact-row").removeClass() }) })