Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why user_permissions does not return any thing?
Here is my scenario: from django.contrib.auth import get_user_model from django.contrib.auth.model import Permission, Group from django.contrib.contenttypes.models import ContentType user = get_user_model().objects.create(email='example@google.com') group = Group.objects.create(name='group1') content_type = ContentType.objects.get( app_label=get_user_model()._meta.app_label, model=get_user_model()._meta.model_name ) permission = Permission.objects.create( name='perm1', codename='perm1', content_type=content_type ) group.permissions.add(permission) user.groups.add(group) Question: So why this query doesn't have any results: user.user_permissions.all() Output <QuerySet []> settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] -
ModelAdmin method stops when I reference too deeply
My model has a bunch of websites, each referencing a set of email_addresses. An email should be sent to the email_address of each website, so the email_message and email_address objects share a ManytoMany relationship. I would like to access the properties of the website of the email_address of the email_message, and I would like to do this in the ModelAdmin of an email_message. So there are multiple levels of references being used here. This is a highly simplified version of my code so please let me know if you need to see something I've omitted. models.py class Email_message(models.Model): email_addresses = models.ManyToManyField(Email_address, related_name='email_messages') subject = models.CharField(max_length=50) body = models.TextField() date_time = models.DateTimeField(null=True, blank=True) class Email_address(models.Model): address = models.EmailField() contact_name = models.CharField(max_length=50, null=True, blank=True) website = models.ForeignKey(Website, on_delete=models.CASCADE, related_name='email_addresses', null=True) class Website(models.Model): domain = models.URLField(default=None) searches = models.ManyToManyField(Search, related_name='websites', blank=True) def __str__(self): return self.domain @property def get_likely_location(self): searches = self.searches.all() locations = [] for search in searches: if search.location is not None: locations.append(search.location) return max(set(locations), key = locations.count) admin.py class Email_messageAdmin(admin.ModelAdmin): fields = ['id', 'email_addresses', 'date_time', 'subject', 'body', 'preview_random_email'] readonly_fields = ['id', 'preview_random_email'] def preview_random_email(self, obj): print("This always prints") test = obj.email_addresses.first().searches.all() print("If things are working, this will print") return format_html(test) I'd … -
Django. Where from my forms.py shall know, that the user has changed the application language?
I have a working application in English. I have started translating it into second language. I have created a language selection menu, which changes the language and it works for templates. In order to translate the fields in the tables (models) I have installed django-modeltranslation and translated all the fields via admin interface. The problem is that my forms.py returns always english text and does not switch to the second language irrespective of the language settings. from django import forms from .models import Application from django.utils.translation import gettext as _ class InputDataWaterForm(forms.Form): '''Application''' choices = list(Application.objects.values_list('id','application')) application = forms.ChoiceField(choices = choices, initial="1", label=_("Specify application:")) ... With the function translation.get_language() in the forms.py I see that the language setting within my forms.py is always en-us. When I force language change within the forms.py via translation.activate("ru"), it perfectly works. Where from my forms.py shall know, that the user has changed the application language? Thank you. -
Cyrillic turned to a question mark | Django template HTML metatags
So after deployment my cyrillic description in html metatags turned into question marks. It works fine on my localhost. Im passing html metatags through admin panel as a model so I can change my metatags after deployment easily, in addition to internationalization purposes. Using MySQL Django 2.2.5/Python 3.7.5 models.py class Metatags(models.Model): metatags_en = models.TextField(verbose_name='English Metatags', null=True) metatags_ru = models.TextField(verbose_name='Russian Metatags', null=True) metatags_uz = models.TextField(verbose_name='Uzbek Metatags', null=True) metatags_oz = models.TextField(verbose_name="O'zbek Metatags", null=True) metatags_en_blog = models.TextField(verbose_name='English Blog Metatags', null=True) metatags_ru_blog = models.TextField(verbose_name='Russian Blog Metatags', null=True) metatags_uz_blog = models.TextField(verbose_name='Uzbek Blog Metatags', null=True) metatags_oz_blog = models.TextField(verbose_name="O'zbek Blog Metatags", null=True) class Meta: verbose_name_plural = _("Metatags") base.html {% for x in metatags %} {% if current_lang == 'en' %}{{x.metatags_en|safe}} {% elif current_lang == 'ru' %}{{x.metatags_ru|safe}} {% elif current_lang == 'uz' %}{{x.metatags_uz|safe}} {% elif current_lang == 'oz' %}{{x.metatags_oz|safe}} {%else%}{{x.metatags_ru}} {%endif%} {%endfor%} metatags I'm using in cyrillic <!-- Primary Russian Meta Tags --> <meta name="title" content="Лорем ипсум долор"> <meta name="description" content="Лорем ипсум долор сит амет, пер цлита поссит ех."> <meta name="keywords" content="Лорем ипсум долор сит амет"> <meta name="robots" content="index, follow"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <meta name="revisit-after" content="1 days"> <meta name="author" content="Лорем"> -
PK not set to model entity after `.save()` in Django
I encountered the error save() prohibited to prevent data loss due to unsaved related object 'artwork'., while trying to add (not update) an Artwork. Originating from this function on ArtworkManager: def save_model(self, request, obj, form, change): super().save_model(request, obj, form, change) obj.save() # obj.id is empty here? try: latest_state = ArtworkState.objects.filter(artwork=obj).latest() except ArtworkState.DoesNotExist: latest_state = None if (latest_state is None or obj.state != latest_state.state): ArtworkState.objects.create( artwork = obj, created_by = request.user, state = obj.state ) The obj.save() seems to work but the obj pk/id does not get set. Artwork has the pk field: id = models.IntegerField(primary_key=True, help_text='') I understand the above error, we canno save a relation that has no primary key. I thought to mitigate that by obj.save()? -
Django: feed path based on category
In my blog I would like to have a feed generator for new posts based on the categories. I've two simple model in models.py: class Category(models.Model): category_name = models.CharField(....) slug_category = models.SlugField(....) publishing_date = models.DateTimeField(....) def __str__(self): return self.category_name def get_absolute_url(self): return reverse("single_blogcategory", kwargs={"slug_category": self.slug_category}) class Post(models.Model): title = models.CharField(....) slug_post = models.SlugField(....) description = models.TextField(....) draft = models.BooleanField(....) category = models.ForeignKey(Category, ....) publishing_date = models.DateTimeField(....) def __str__(self): return self.title def get_absolute_url(self): return reverse("single_blogpost", kwargs={ "slug_post": self.slug_post, "slug_category": self.category.slug_category, }) In views.py I have this situation: post_filter = BlogPost.objects.filter(Q(draft=False) & Q(publishing_date__lte=timezone.now())) def categoryList(request): category_list = BlogCategory.objects.all() context = {"category_list": category_list} return render(request, "blog/list_categories.html", context) def singleCategory_postList(request, slug_category): category = get_object_or_404(BlogCategory, slug_category=slug_category) blogpost_full = post_filter.filter(category=category) paginator = Paginator(blogpost_full, 10) page = request.GET.get("pagina") post_list = paginator.get_page(page) context = { "category": category, "post_list": post_list, } return render(request, "blog/single_category.html", context) def singlePost(request, slug_post, slug_category): category = get_object_or_404(BlogCategory, slug_category=slug_category) blogpost = get_object_or_404(post_filter, slug_post=slug_post) category_blogpost = BlogPost.objects.filter(category=category) context = { "category": category, "blogpost": blogpost, "category_blogpost": category_blogpost } return render(request, "blog/single_post.html", context) This is feed.py: class RssSiteNewsFeedBlogCategory(Feed): title = "Nuovo articolo online!" link = "/sitenews/" description = "Ultime news" def items(self): return BlogCategory.objects.filter(slug_category=slug_category).order_by('-publishing_date')[:5] def item_title(self, item): return item.title def item_pubdate(self, item): return item.publishing_date def item_description(self, item): return … -
Django: real time database using channels
I'm looking into channels lately in Django and from what I see in all the examples it is used for chat like applications. But I was wondering if I can use it to push notifications about database changes. So for example, what if my "view" consumer would poll the database and push notification every time it changed to the client. It is as if all clients of that page connect to the same chat room and wait for "posts" from the server. I know I can poll from the client using Ajax but I was wondering if I can use Django channels for that and have the server do the polling. -
django what do i need for authentication after login?
I followed the example in: https://docs.djangoproject.com/en/3.0/topics/auth/default/#django.contrib.auth.login from django.contrib.auth import authenticate, login def my_view(request): username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) # Redirect to a success page. ... else: # Return an 'invalid login' error message. This code doesn't seem to return any token or some sort to the client but just a redirection. In other codes where django checks authentication, django checks request.user.is_authenticated. Do i need to set this by myself? from django.conf import settings from django.shortcuts import redirect def my_view(request): if not request.user.is_authenticated: return redirect('%s?next=%s' % (settings.LOGIN_URL, request.path)) To get authenticated by decorators such as @login_required or have proper value for request.user.is_authenticated, what do I need to send and receive from the client(ReactJS)? -
Django insert one-to-one field only with its primary key?
When I try to create a basic post, it requires me to pass all the information about the author. post request body: { "author": { "id": 1 }, "title" : "title1", "content": "content1" } error message: { "author": { "username": [ "This field is required." ], "password": [ "This field is required." ], "profile": [ "This field is required." ] } } Is it possible to assign author only by its user id like I tried in the example above? class BasicPost(models.Model): author = models.OneToOneField(User, null=True, on_delete=models.SET_NULL, related_name='author') title = models.TextField() content = models.TextField() created_at = models.DateTimeField(default=timezone.now) modified_at = models.DateTimeField(default=timezone.now) -
Loop through django queryset in Javascript
I'm new to Django and I need to use some JS for my site, but i'm having a hard time understanding it. This is my view, where i am passing 'seats' to my template seats = Seat.objects.filter(screen = screen) seats = serializers.serialize('json', list(seats), fields = ('position', 'status')) context = {'seats': seats} return render(request, 'cart/choose_seat.html', context) This is 'seats' printed What i want to do is print the position of each seat object. So far, i've only written this: <script> var seats = "{{seats}}"; function position() { for (var i=0; i<seats.length; i++){ var obj = seats[i]; document.write(obj) } } </script> So, what should i do to print position? Thanks in advance -
Is bash_profile a shared file? Can SECRET_KEYs be shared between 2 projects?
Working on deploying the two Django projects I've developed, I deployed the first one and ran atom ~/.bash_profile in command line venv to set my SECRET_KEY and DEBUG values. I was able to deploy that app and its up and running fine. Then I went to deploy my second project and used the same command line script to open bash_profile and the SECRET_KEY and DEBUG values from the previous project is what came up. Is bash_profile a shared file? Am I supposed to have the same SECRET_KEY values for two different projects? -
Django FileResponse from io.BytesIO()
I have a view that serves PDF files, but I would like to modify the metadata of the pdfs before sending them. This is what I have so far: import i from django.http import FileResponse, StreamingHttpResponse from PyPDF2 import PdfFileReader, PdfFileWriter def doc_view(request): handle = open("documents/foo.pdf", "rb") base_pdf = PdfFileReader(handle) output_pdf = PdfFileWriter() for page in base_pdf.pages: output_pdf.addPage(page) stream = io.BytesIO() output_pdf.write(stream) stream.seek(0) return FileResponse(stream.read(), content_type="application/pdf") Running stream.read() manually returns a bytes object, which looks like it is ASCII encoded (but not certain of that). The view completes successfully, and returns a 200, but the PDF received by the browser cannot be displayed (it seems to be corrupted somehow). -
Django Rest Framework — no module named rest_framework
I am build a backend for my Nuxt.js project and I installed the following packages: django django-rest-framework django-cors-headers I installed them using pip3 but when I am trying to run migrations I get the following error: ImportError: No module named 'rest_framework' I checked my settings.py and I have everything as it should be. Do you guys have an idea how to solve this? -
Retrieve and update field of a model on views and display updated field in template
I am working on a view that retrieves the field(user's score) that is declared in a model, where I will also update the field(user's score) after a simple if-else statement, then display the field in template. But now, in the template's text area, where I put the result, it is now only showing userScore: userScore object (1), False, instead of the value of the user's score. So, how can I retrieve the score of the user from the model and update the field in views? morse_logs/game1.html {% block content %} <title>GAME 1</title> <h1>GAME 1</h1> <h2>1 + 1 = ?</h2> <form action="" method="get" > <input type="number" id="ans1" name="ans1"/><br><br> <button type="submit" name="game1Answer">Submit</button><br><br> <textarea rows="10" cols="50" name='a2' > {{currentS}} </textarea> </form> </div> {% endblock content %} morse_logs/views.py @login_required() def game1(request): if request.user and not request.user.is_anonymous: user = request.user #else: #Throw some raised exception here as the user is not valid... """The Game 1 page""" def verifyGame1(val1): user_score = userScore.objects.get_or_create(user=user) if val1 == 2: #user's score declared in model increase 5points #display correct and 5 points added to user user_score.score += 5 #user_score = str(user_score) user_score.save() return user_score else: #user's score declared in model has no point #display incorrect and 1 point added to … -
Executing a function from a third party package when a Record/Domain model is saved
I've been stuck on this for over a day now. Here is the function I want to execute: https://github.com/gnotaras/django-powerdns-manager/blob/master/src/powerdns_manager/utils.py#L551 rectify_zone As you can see, it saves the model, so if I put it in save(), or a presave or postsave signal, it will result in infinite recursion. In the package, a signal is automatically executed when a Domain or Record is saved in the admin, but not anywhere else. I want to be able to run rectify_zone outside of the admin. At the moment I'm stumped. Can anyone help? Thanks in advance. -
Error : MultiValueKeyError at /quiz/2/11 'choice'
I am creating a multi-choice quiz app, I have created a view which shows the question and its 4 option I have given radio button to each option but is giving me this error:MultiValueDictKeyError at /quiz/2/11/ 'choice' views.py def question_detail(request,question_id,quiz_id): q = Quiz.objects.get(pk=quiz_id) que = Question.objects.get(pk=question_id) ans = que.answer_set.all() selected_choice = que.answer_set.get(pk=request.POST['choice']) if selected_choice is True: come = que.rank came = come + 1 later_question = q.question_set.get(rank=came) return render(request,'app/question_detail.html',{'que':que , 'later_question':later_question, 'ans':ans}) else: come = que.rank later_question = q.question_set.get(rank=come) return render(request, 'app/question_detail.html', {'que': que, 'later_question': later_question, 'ans': ans}) question_detail.html <form action="{% 'app:detail' quiz_id=quiz.id question_id=que.id %}" method="post"> {% csrf_token %} {% for choice in que.answer_set.all %} <input type="radio" name="choice" id="choice{{forloop.counter}}" value="{{choice.id}}"> <label for="choice{{forloop.counter}}">{{choice.answer}}</label> {% endfor %} -
Django, Post Form Data Not Binding or Received By View
My view is not receiving and binding the data from the form. The goal of the form page is standard. Form Page loads without errors, user inputs data, if errors form is reloaded with prior user data and errors called out. If Form is valid it saves data to the DB. I have followed the Django Form documentation, and read through Stack Overflow threads, but have not been able to achieve the above behavior. FORM.PY from django import forms class templateForm(forms.Form): TemplateName = forms.CharField(max_length=50) Descriptions = forms.CharField(initial="User Name & Date") Contents = forms.CharField(required= False, max_length=50, widget=forms.HiddenInput()) CPU_Quantity = forms.IntegerField(initial=1) Memory_Quantity = forms.IntegerField(initial=12) VIEWS.PY class Add_Server_Template(View): def post (self, request): #If this is a POST then process the form data if request.method == 'POST': ### Binds user data to form form = templateForm(request.POST) if form.is_valid(): # <process form cleaned data> model_instance = form.save(commit=False) model_instance.save() return render(request, "Server_Template/index.html", {'form': form}) ### if form is not valid. Re-render form with user data. else: form = templateForm() return render(request, 'Server_Template/index.html', {'form': form}) URLS.PY url(r'serverstructure/add/$', views.Add_Server_Template.as_view(), name='serverStructure-Add'), TEMPLATE Configtempaltes.html {% extends 'Server_Template/base.html' %} {% block body %} {% load bootstrap4 %} <div class="container-fluid" > <div class="row"> <div class="col-sm-4 col-sm-offset-1" > <h3>Server Template</h3> </div> </div> <div … -
How to change filter queryset depends on user
I am using django-filter and I have two models CustomUser and Shop. How to change filter choices queryset so that user(request.user) can filter only his shops? User class CustomUser(AbstractBaseUser, PermissionsMixin): shop = models.ManyToManyField(Shop, blank=True, related_name='custom_user') Shop class Shop(models.Model): address = models.CharField(_('Address'), unique=True, max_length=64, blank=False, null=False, db_index=True) filters.py shops = Shop.objects.filter(is_active=True) SHOP_CHOICES = [('All', 'All')] for x in shops: SHOP_CHOICES.append((x.address, x)) SHOP_CHOICES = tuple(SHOP_CHOICES) class ShopFilter(django_filters.FilterSet): address = django_filters.MultipleChoiceFilter(choices=SHOP_CHOICES) class Meta: model = Shop fields = ['address'] views.py f = ShopFilter(request.GET) -
Django: drop-down-box
My forms.py has this: SIZE_CHOICES = ( ('s', 'Small'), ('m', 'Medium'), ('l', 'Large') ) class ChooseSize(forms.Form): size_choice = forms.ChoiceField(choices=SIZE_CHOICES) My product_page.html tries to implement this form: <form method="POST" class="card-body"> {% csrf_token %} <div> {{ form.size_choice }} </div> </form> For some reason size_choices doesn't show up on the web-page. What gives? -
DJANGO - Extract filtered data to excel
I have a view for filtering data and display it in a table. I would like to export the filtered data to excel. I wrote the view for exporting but I don't know how to connect the two. OrderFilter is a django-filter Views.py def data(request): orders= Order.objects.all() filter= OrderFilter(request.GET, queryset=Order.objects.all()) orders= filter.qs.order_by('-Date','-Hour') return render(request, 'template.html',{'orders':orders,'filter': filter}) def export_data(request): response = HttpResponse(content_type='application/ms-excel') response['Content-Disposition'] = 'attachment; filename="data.xls"' wb = xlwt.Workbook(encoding='utf-8') ws = wb.add_sheet('Data') # Sheet header, first row row_num = 0 font_style = xlwt.XFStyle() font_style.font.bold = True columns = ['Date', 'Hour', 'Category', 'Item'] for col_num in range(len(columns)): ws.write(row_num, col_num, columns[col_num], font_style) # Sheet body, remaining rows font_style = xlwt.XFStyle() rows = Order.values_list('Date', 'Hour', 'Category', 'Item__Item') for row in rows: row_num += 1 for col_num in range(len(row)): ws.write(row_num, col_num, row[col_num], font_style) wb.save(response) return response -
How to declare common variables for all methods of a Django class-based view?
I have a class-based view in my Django application and it works fine. But I guess it is not coded well, because it violates the DRY principle. Specifically, I have two absolutely similar declarations of the posts_list variable inside get() and post() methods: class TopicView(View): def get(self, request, topic_id): post_form = PostForm() posts_list = Post.objects.filter(topic_id=self.kwargs['topic_id']).order_by('-creation_date') return render(request, 'discussions/topic.html', {'posts_list': posts_list, 'post_form': post_form, 'topic_id': topic_id}) def post(self, request, topic_id): post_form = PostForm(request.POST) if post_form.is_valid(): post = post_form.save(commit=False) post.author = request.user post.topic = Topic.objects.get(pk=topic_id) post.save() return redirect('discussions:topic', topic_id=topic_id) posts_list = Post.objects.filter(topic_id=self.kwargs['topic_id']).order_by('-creation_date') return render(request, 'discussions/topic.html', {'posts_list': posts_list, 'post_form': post_form, 'topic_id': topic_id}) Is there a way how I can declare this variable as a class attribute instead of a simple variable inside each of the methods? When I declaring it, I use topic_id as a filter for objects, and I extract topic_id from the URL (self.kwargs object, self is passed to both get() and post() as an input parameter). This is the main issue. -
How do I display user profile pic if saved in custom directory?
I have created an app called users and have created a custom method called get_upload_path. I am using this method to allow users to upload profile pics to a custom path for better organization of images. What should I change in MEDIA_URL so that these images will be displayed on a custom template? users/models.py: from django.db import models from django.contrib.auth.models import User def get_upload_path(instance, filename): return '%s/%s' % (instance.user.username, filename) class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) # make bio and other stuff here image = models.ImageField(default='default.jpg', upload_to=get_upload_path) def __str__(self): return f'{self.user.username} Profile' settings.py: # Directory where uploaded files will be saved MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' users/templates/users/profile.html {% extends 'blog/base.html' %} {% load crispy_forms_tags %} {% block content %} <div class="content-section"> <div class="media"> <img class="rounded-circle account-img" src="{{ user.profile.image.url }}"> <div class="media-body"> <h2 class="account-heading">{{ user.first_name }} {{ user.last_name }}</h2> <p class="text-secondary">{{ user.email }}</p> </div> </div> <!-- FORM HERE --> </div> <p class="text-muted">Joined on: {{ user.date_joined|date:"F d, Y" }}</p> <p class="text-muted">Last logged in on: {{ user.last_login|date:"F d, Y" }}</p> {% endblock content %} File Structure: -
how to serve django with react frontend using webpack?
I used webpack to convert react to static files and render them in django templates but even though the static files are changed the website rendered by django is same -
Errors with models in django, creating events registration app
i am creating django app that allows users to register to different events. I created one Registration model in .models and added specific views but i have got some model errors. Wondered if anyone could help out a little? I am also not 100% sure if i have done all code correctly because i am quite new to django. Thanks a lot! Here is my model file: from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse import datetime class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) hardness_level = models.TextField(max_length=20, default='easy') author = models.ForeignKey(User, on_delete=models.CASCADE) location = models.CharField('location', max_length=150) info = models.TextField() starts = models.DateTimeField('Starts') ends = models.DateTimeField('Ends') arrive_when = models.DateTimeField('Arrival time', null=True, blank=True) arrive_where = models.CharField('Arrival location', null=True, max_length=150, blank=True) registration_starts = models.DateTimeField('Registration start') registration_limit = models.IntegerField('Guest limit', default=0, choices=[(0, u"No limit")] + list(zip(range(1, 100), range(1, 100))), on_delete=models.CASCADE()) def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) class Meta: verbose_name = "event" verbose_name_plural = "events" ordering = ['-starts'] def __str__(self): if self.starts.date() != self.ends.date(): return u"%s, %s - %s" % (self.title, self.starts.strftime("%a %H:%M"), self.ends.strftime("%a %H:%M")) else: return u"%s, %s - %s" % (self.title, self.starts.strftime("%H:%M"), self.ends.strftime("%H:%M")) def get_registrations(self): return EventRegistration.objects.filter(event=self) … -
How to add a row ID in django-tables to get the selected radio button from the specific row
I am trying to use the jQuery to get the row that selected radio is in and also the selected radio button value when using django-tables2. So, I have three columns in a table and I rendered it with django-tables2. The third columns is templatecolumn with the HTML template (buttons.html: <form class="myForm"> <input type="radio" class="Yes" name="result" value="Yes"> <label for="Yes">Yes</label> <input type="radio" class="No" name="result" value="No"> <label for="No">No</label><br> </form> I then add templatecolumn to the table ( I created my own table class by inheriting from tables.Table): myTableCol={} mylist = [] for i in queryResults: mydic = {} for j in i: className=str(type(j)).split(".")[1] mydic.update({className: j.name}) myTableCol.update({className: tables.Column()}) mylist.append(mydic) myTableCol.update({'Action': tables.TemplateColumn(template_name="buttons.html", verbose_name=("Actions"), orderable=True)}) Meta = type('Meta', (object,), {'template_name':"django_tables2/bootstrap4.html", 'attrs':{"class": "paleblue"},}) myTableCol.update({'Meta':Meta}) QueryTable2=type('QueryTable', (tables.Table,), myTableCol) The table is then rendered using {% render_table table %} that gives the html below. I am trying to get which radio button that was selected for the row. $(document).ready(function () { $('input').click(function() { var $selectedButton = $('input[name=result]:checked').val(); var $row = $(this).closest("tr"); var $rowData = $row.children("td").map(function() { return $(this).text(); }).get(); alert($selectedButton); });}); <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> <div class="table-container"> <table class="paleblue"> <thead class="thead-default" > <tr> <th class="orderable"> <a href="?sort=UseCase">UseCase</a> </th> <th class="orderable"> <a href="?sort=MainFlow">MainFlow</a> </th> <th class="orderable"> <a href="?sort=Action">Actions</a> </th> </tr> </thead> …