Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Specifying basic authentication credentials for a Django REST framework API client
I'm trying to run some tests to go with the Django REST tutorial (see source code). I got a solution working using the APIClient's .force_authenticate method, but I'd prefer to construct the credentials more explicitly. I've tried the following: import json import base64 from django.contrib.auth.models import User from django.test import TestCase from rest_framework.test import APITestCase, force_authenticate from snippets.models import Snippet class SnippetTestCase(APITestCase): def setUp(self): self.username = 'john_doe' self.password = 'foobar' self.user = User.objects.create(username=self.username, password=self.password) # self.client.force_authenticate(user=self.user) credentials = base64.b64encode(f'{self.username}:{self.password}'.encode('utf-8')) self.client.credentials(HTTP_AUTHORIZATION='Basic {}'.format(credentials)) def test_1(self): response = self.client.post('/snippets/', {'code': 'Foo Bar'}, format='json') self.assertEqual(response.status_code, 201) This test passed with the commented-out line with .force_authenticate, but fails in its current form, which I based on Using Basic HTTP access authentication in Django testing framework: Kurts-MacBook-Pro:rest-framework-tutorial kurtpeek$ python manage.py test Creating test database for alias 'default'... System check identified no issues (0 silenced). F ====================================================================== FAIL: test_1 (tutorial.tests.SnippetTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/Users/kurtpeek/Documents/source/rest-framework-tutorial/tutorial/tests.py", line 23, in test_1 self.assertEqual(response.status_code, 201) AssertionError: 403 != 201 ---------------------------------------------------------------------- Ran 1 test in 0.022s FAILED (failures=1) Apparently, the authentication is not working because I'm getting a 403 Forbidden error. Any ideas on how to fix this? -
How can send data from nodemcu/arduino to raspberry pi via wifi?
I made a webapp using django framework and setup a web server in raspberry pi 3 following this tutorial(using gunircon and nginx), also a set up the raspberry as access point.In the other hand, I have sensor that is measuring, this sensor was made using Nodemcun and de Arduino IDE,I want send de data from nodemcu to rapsberry pi via WiFi and get de data in raspberry and save it in my database, my question is howt to do it using python? I have been reading and I found that that is possible using telnet but I don't know how to do it. some clue, information or tutorial pleas. Thanks a lot -
How to handle legacy php-generated passwords in Django
I'm moving a server from php(5.6.32) to Django(1.11.7) that contains thousands of users with passwords encrypted using the password_hash(<pwd>, PASSWORD_DEFAULT) function. Does Django have support for this encryption? It appears neither theBCryptPasswordHasher or the BCryptSHA256PasswordHasher handle this. I believe a custom hasher may be required, but its not clear how to handle this. -
Django: displaying a foreign key of a model in template
this is a rather basic question (I'm new to Django) i'm having trouble displaying a foreign key in the template. i have this model which has 'employer' as a ManyToManyField in the Job model: from django.db import models # Create your models here. class Employer(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=50,default="") business = models.CharField(max_length=25, default="") team = models.IntegerField() about = models.TextField(max_length=1000) country = models.CharField(max_length=25, default="") city = models.CharField(max_length=25, default="") class Job(models.Model): date = models.DateTimeField(auto_now_add=True, blank=True) specialism = models.CharField(max_length=25) employer = models.ManyToManyField(Employer) I try to get all jobs that contains "Computers" as specialism: from django.shortcuts import render from .models import Job, Employer # Create your views here. def index(request): return render(request, 'pages/index.html') def post_list(request): jobs = Job.objects.all().filter(specialism="Computers") return render(request, 'wall.html',{'jobs':jobs}) And for every job i wanna display the employer name in the template: <!DOCTYPE html> <html> <head> <title></title> </head> <body> <center><h1>WALL</h1></center> {% block content %} {{jobs.count}} {% for job in jobs %} <h2>specialism :{{job.specialism}} employer: {{job.employer.name}}</h2> {% endfor %} {% endblock %} </body> </html> I get None as a value for job.employer.name. so how can i display the name of the employer for every job? -
Django: I cant create a model, I got this error:[pylint] E0001:invalid syntax (<string>, line 8)
file: models.py from __future__ import unicode_literals from django.db import models class Register(models.Model) name =models.Charfield(maxlength=100,blank=True,null=True) email =models.EmailField() timestamp = models.DateTimeField(auto_now_add=True,auto_now=False) def__unicode__(self): return self.mail def__str__(self): return self.mail error: [pylint] E0001:invalid syntax (, line 8) I try to execute command-line: python manage.py makemigrations message is: No changes detected. I use python 3.7 -
Adding tests to the Django REST framework tutorial
I'm trying to replace an existing function-based view using the login_required decorator with a Django REST framework API using a ModelViewSet. However, it seems like the authentication works a bit differently. In order to try to adapt my unit tests to the Django REST framework case, I cloned https://github.com/encode/rest-framework-tutorial and added a tests.py at the top level directory: import json from django.contrib.auth.models import User from django.test import TestCase, Client from snippets.models import Snippet class SnippetTestCase(TestCase): def setUp(self): self.username = 'john_doe' self.password = 'foobar' self.user = User.objects.create(username=self.username, password=self.password) self.client = Client() self.snippet = Snippet.objects.create(owner=self.user, code="Foo Bar") def test_1(self): self.client.login(username=self.username, password=self.password) response = self.client.post( path='http://localhost:8000/snippets/1/', data=json.dumps({'code': 'New code'}), content_type="application/json") self.assertEqual(response.status_code, 201) However, this returns a 403 Forbidden response: Kurts-MacBook-Pro:rest-framework-tutorial kurtpeek$ python manage.py test Creating test database for alias 'default'... System check identified no issues (0 silenced). F ====================================================================== FAIL: test_1 (tutorial.tests.SnippetTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/Users/kurtpeek/Documents/source/rest-framework-tutorial/tutorial/tests.py", line 23, in test_1 self.assertEqual(response.status_code, 201) AssertionError: 403 != 201 ---------------------------------------------------------------------- Ran 1 test in 0.049s FAILED (failures=1) Destroying test database for alias 'default'... On the other hand, using HTTPie with the -a flag works fine: Kurts-MacBook-Pro:rest-framework-tutorial kurtpeek$ http -a kurtpeek:foobar123 POST http://localhost:8000/snippets/ code="print 123" HTTP/1.1 201 Created Allow: GET, POST, HEAD, OPTIONS … -
Linking user to other tables in django
I have the below in my models.py file: class Film(models.Model): title = models.CharField(max_length=200) director = models.CharField(max_length=200) description = models.CharField(max_length=200) pub_date = models.DateField('date published') class Comment(models.Model): film = models.ForeignKey(Film, on_delete=models.CASCADE) body = models.CharField(max_length=200) When I logged into Django admin I added some films, and then added some comments, selecting which film object the comment related to. I then created a couple of users via the admin panel also. I would like my relationships to be: Film can have many comments / Comments belong to film User can have many comments / Comments belong to user I think, like with comments and films, I just need to define user as a foreign key to comment. I am struggling to do this. I am working through the Django tutorials but I can't see the tutorials covering how I can link other tables to the user. I thought I would be able to do something like this: user = models.ForeignKey(User, on_delete=models.CASCADE) While importing User like this: from django.contrib.auth.models import User The result at the moment is if I keep user = models.ForeignKey(User, on_delete=models.CASCADE) I get err_connection_refused -
disable logout after adding user django
I need to create admin panel in django , admin will be able to add students"which extended from users " , I finally be able to add them , but after that I get "'AnonymousUser' object has no attribute '_meta' User is added to the database correctly , But django logged me out ! How Can I keep my current user session ! class student(models.Model): Computers = 1 Communications = 2 Dep_CHOICES = ( (Computers, 'Computers'), (Communications, 'Communications'), ) user = models.OneToOneField(User, on_delete=models.CASCADE) dep = models.PositiveSmallIntegerField(choices=Dep_CHOICES, null=True, blank=True) deg = models.FloatField(null=True, blank=True) def __str__(self): # __unicode__ for Python 2 return self.user.username def create_user_profile(sender, instance, created): if created: student.objects.create(user=instance) def save_user_profile(sender, instance , **kwargs): instance.student.save() class UserForm(ModelForm): class Meta: model = User fields = ('username', 'email', 'password') class studentForm(ModelForm): class Meta: model = student fields = ('dep', 'deg') The view def add_stu(request): if request.method == 'GET': return render(request, "add_student.html") else: user_form = UserForm(request.POST, instance=request.user) profile_form = studentForm(request.POST, instance=request.user.student) user_form.save() profile_form.save() -
pytest django TestCase give strange failures
I have a very simple class which fails on any version of pytest>3.0.0. from django.test import TestCase class TestTestCase(TestCase): """Tests for the TestCase class.""" def test_that_client_exists(self): """Assert that the class has a client.""" assert self.client I am using the following version: platform Linux Python 2.7.11 pytest-3.3.1 py-1.5.2 pluggy-0.6.0 django-2.9.2 And I get the following error: self = <myproject.tests.test_test_case.TestTestCase testMethod=test_that_client_exists> def test_that_client_exists(self): """Assert that the class has a client.""" > assert self.client E AttributeError: 'TestTestCase' object has no attribute 'client' However, if I downgrade to pytest==3.0.0 and pluggy-0.3.1, the code executes without any issues. My question is this, what is going on? What could be causing this? It is as if pytest is calling the test_that_client_exists but is not calling __call__ which calls _pre_setup. Has anyone seen anything like this? -
Django Form: NoReverseMatch
Getting an error: NoReverseMatch: Reverse for 'post_new' not found. 'post_new' is not a valid view function or pattern name. my form in base.html: > <form action="{% url 'post_new' %}" method="post"> > {% csrf_token %} > Name:<br> > <input type="text" name="name"><br> > Text:<br> > <input type="text" name="text"> > <input type="submit" value="Submit"> </form> views.py: def post_new(request): posts = Post.objects.all() name = request.POST['name'] print(name) return render(request, 'blog/base.html', {'posts': posts}) urls.py: urlpatterns = [ url(r'^$', views.base), url(r'^post_new/$', views.post_new, name='post_new'), ] -
Pass JSON data in Django context
Normally, if I want to return JSON data from a Django view, I can use a JsonResponse like so: from django.http import JsonResponse def my_view(request): return JsonResponse({'my_key': 'my_value'}) That data is sent to the frontend as a JavaScript object that I can immediately use. I'd like that same ease of use added to the context of a view, like so: class WebsiteView(TemplateView): template_name = 'index.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['my_var'] = {'my_key': 'my_value'} return context However, rendering the template with {{ my_var }} gives: {&quot;my_key&quot;: &quot;my_value&quot;} Ultimately, what I want is for {{ my_var }} to return the plain string rather than the HTML encoded version: {"my_key": "my_value"} This way, I can easily load it into a JavaScript object with JSON.parse('{{ my_var }}'). I know that one way to achieve this is by manually unescaping the HTML entities, but I was wondering if there was a better way to do this. -
Setting up Ubuntu Server 16.04 with Apache to run Django
I have Ubuntu Server 16.04 running Achape. I am trying to get Apache to run Django. So far I have created a project in Django and can get it to run on port 80 by using the command "sudo python3 manage.py runserver 192.168.1.230:80". I would like to have Apache setup to run Django so I do not have to do this command. I have looked for 6 hours now and tried 10+ different ways to do this and can't get it to work. I usually end up getting a 500 Internal Error. I have changed the apache2.conf file, and 000-default.conf file. What should I do? -
troubles modules Django mas os - pycharm
dears. I'm new in python/django. I just try Install and configure an enviroment from my ubuntu to my mac os. I've installed Python 3.6 , Django 2.0 and i'm using pycharm. When I tried run with "runserver", I got this error: /Users/fabio/Documents/projects/lib/python3.6/site-packages/magic/__pycache__/_cffi__xa0d5132dx54cebdac.c:208:10: fatal error: 'magic.h' file not found #include <magic.h> ^~~~~~~~~ 1 error generated. /Users/fabio/Documents/projects/lib/python3.6/site-packages/magic/__pycache__/_cffi__xa0d5132dx54cebdac.c:208:10: fatal error: 'magic.h' file not found #include <magic.h> ^~~~~~~~~ 1 error generated. Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x10ea68268> Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/distutils/unixccompiler.py", line 118, in _compile extra_postargs) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/distutils/ccompiler.py", line 909, in spawn spawn(cmd, dry_run=self.dry_run) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/distutils/spawn.py", line 36, in spawn _spawn_posix(cmd, search_path, dry_run=dry_run) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/distutils/spawn.py", line 159, in _spawn_posix % (cmd, exit_status)) distutils.errors.DistutilsExecError: command '/usr/bin/clang' failed with exit status 1 During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Users/fabio/Documents/projects/lib/python3.6/site-packages/cffi/ffiplatform.py", line 55, in _build dist.run_command('build_ext') File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/distutils/dist.py", line 974, in run_command cmd_obj.run() File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/distutils/command/build_ext.py", line 339, in run self.build_extensions() File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/distutils/command/build_ext.py", line 448, in build_extensions self._build_extensions_serial() File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/distutils/command/build_ext.py", line 473, in _build_extensions_serial self.build_extension(ext) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/distutils/command/build_ext.py", line 533, in build_extension depends=ext.depends) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/distutils/ccompiler.py", line 574, in compile self._compile(obj, src, ext, cc_args, extra_postargs, pp_opts) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/distutils/unixccompiler.py", line 120, in _compile raise CompileError(msg) distutils.errors.CompileError: … -
Django model history by date and datetime
Assume I have model like this: class Account(models.Model): balance = models.IntegerField() debt = models.IntegerField() history = HistoricalRecords() I'm using django-simple-history to get instance of the model as it would have existed at the provided date and time: inst = Account.history.as_of(datetime.datetime.now().date) It's working fine, but I want to get instance where debt field is represented as it would have existed at the provided date and time, and then debt field will be most recent of that date. I don't know if this is possible, didn't find anything about that. -
Prefetch the contents of files referenced by the ORM
My situation is that I'm using the Django ORM to fetch a list of objects, each with a file. I then need to access the file-data for each and every object in the list. We're hosting our files on S3, and it seems to take a long time every time I call f.read() I'm wondering, is there a way to pre-fetch the contents of the file, so that f.read() doesn't have to make another round-trip? Anything else I can do to speed this up? Any help is appreciated, and let me know if there is more I can clarify. -
How to update a Wagtail Page
I am using a wagtail_hook to update a Page object and am running into trouble. More specifically, when an end-user hits the "Save draft" button from the browser I want the following code to fire. The purpose of this code is to change the knowledge_base_id dynamically, based on the results of the conditional statements listed below. def sync_knowledge_base_page_with_zendesk2(request, page): if isinstance(page, ContentPage): page_instance = ContentPage.objects.get(pk=page.pk) pageJsonHolder = page_instance.get_latest_revision().content_json content = json.loads(pageJsonHolder) print("content at the start = ") print(content['knowledge_base_id']) kb_id_revision = content['knowledge_base_id'] kb_active_revision = content['kb_active'] if kb_active_revision == "T": if kb_id_revision == 0: print("create the article") content['knowledge_base_id'] = 456 #page_instance.knowledge_base_id = 456 # change this API call else: print("update the article") elif kb_id_revision != 0: print("delete the article") content['knowledge_base_id'] = 0 #page_instance.knowledge_base_id = 0 print("content at the end = ") print(content['knowledge_base_id']) #page_instance.save_revision().publish So when the hook code fires, it updates the draft with all the info EXCEPT the knowledge_base_id. However when I change the knowledge_base_id like this (seen commented out above) page_instance.knowledge_base_id = 0 And save it like this (also seen commented out above) page_instance.save_revision().publish() It saves the updated knowledge_base_id BUT skips over the other revisions. In short, what the heck am I doing wrong. Thanks in advance for the assist. … -
Retrieving values from backwards relationship as a list of integers instead of list of tuples?
Right now I have a column named 'Value' in my 'Data' model, which has a ForeignKey from 'FOO' model: class FOO(models.Model): label = models.CharField(max_length=10, primary_key=True) ... class Data(models.Model): label = models.ForeignKey(Tickers, on_delete=models.CASCADE) Volume = models.FloatField(default=0) ... I'm fetching related objects as follows: v = FOO.objects.get(pk='something') vol = v.foo_set.values_list('Volume') and a get a list of tuples, which, afterwards, I have to convert to list integers with list comprehension. Is there a more elegant way to get a list of integers directly? Thanks -
Token based authentication not using JWT?
Whats a good practice for developing token based authentication for my app not using JWT? -
How to deserialize nested serializers with Django Rest Framework
i have in models.py class Variants(Model): class Meta: db_table = 'variants' id = models.AutoField(primary_key=True) name = models.CharField(max_length=255, blank=False, null=False) client = models.ForeignKey(Client, on_delete=models.CASCADE, null=False, blank=False) created_at = models.DateField(auto_created=True, default=now, blank=True) updated_at = models.DateField(auto_now=True, null=True, blank=True) and class VariantOptions(Model): class Meta: db_table = 'variant_options' id = models.AutoField(primary_key=True) name = models.CharField(max_length=255, blank=False, null=False) variant = models.ForeignKey(Variants, on_delete=models.CASCADE, null=False, blank=False) created_at = models.DateField(auto_created=True, default=now, blank=True) updated_at = models.DateField(auto_now=True, null=True, blank=True) and in serializers.py class VariantOptionsSerializer(serializers.ModelSerializer): class Meta: model = models.VariantOptions fields = ['name'] class VariantsSerializer(serializers.ModelSerializer): options = VariantOptionsSerializer(many=True) class Meta: model = models.Variants fields = ['name','client','options'] def create(self, validated_data): options_data = validated_data.pop('options') variant = models.Variants.objects.create(**validated_data) for option_data in options_data: models.VariantOptions.objects.create(variant=variant, **option_data) return variant and my view class VariantsCreate(APIView): permission_classes = (permissions.IsAuthenticated,) serializer_class = serializers.VariantsSerializer def post(self, request, format=None): serializer = serializers.VariantsSerializer(data=request.data) if serializer.is_valid(): saved = serializer.save() return Response(serializer.data) ==> serializer.data gives error return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) i have this error Got AttributeError when attempting to get a value for field options on serializer VariantsSerializer. The serializer field might be named incorrectly and not match any attribute or key on the Variants instance. Original exception text was: 'Variants' object has no attribute 'options'. but the data has already been validated by the call to is_valid() … -
django and mysql - select distinct column with filters
suppose, I have a table with 3 columns: create table t1 (c1 int, c2 int, c3 int) i want to return a list of distinct values of c2 after applying filters on c1, c2 and c3 at the SQL level, I can do this easily: select distinct (c1) from t1 where c1=10 and c2>30 and c3 in (1,2,3) what is the best way to do so in django? I don't want to use .raw SQL since the filters are dynamic and it will be a nightmare to build the appropriate SQL query (there are more than 30 columns in the real table). is there a way to create a queryset with filters against all the table colums that will return only sub columns of the table? if so the distinct() would have worked Thanks for any tip Eyal -
Error: No UserDetails model is Created
I'm trying to reduce the image size before upload. I'm using default User model given by django & linking it to another model just to add few more things to the user profile. This is how models.py looks like, class UserDetails(models.Model): user = models.OneToOneField(User) profile = models.ImageField(upload_to='profile_image', blank=True) ... def save(self, *args, **kwargs): img = Image.open(self.profile) resize = img.resize((240, 240), Image.ANTIALIAS) new_image = BytesIO() resize.save(new_image, format=img.format) temp_name = self.profile.name self.profile.save(temp_name, content=ContentFile(new_image.getvalue()), save=False) super(UserDetails, self).save(*args, **kwargs) Problem is that when I'm signing up with fields username, first_name & password, it's not creating a UserDetails model along with that user. So, if I try to visit any user's profile it gives an error, no UserDetails model is present. If I remove the image compression code from the model & sign up again everything starts working perfectly fine. How can we fix that? Thank You . . . -
Django multiple databases - correct router class
I would like to use two databases in my application: local database external database in the first one I want to save all django tables , e.g auth_group To do this I tried to use router class, but unsuccessfully - it doesn't work. Below you can find my code Django 1.11 setings file: DATABASE_ROUTERS = ['mainApp.models.DefaultDBRouter','subfolder.newApp.models.testDBRouter',] models.py - main app - I want to use default DB for this model from __future__ import unicode_literals from django.db import models class list_a( models.Model ): region = models.CharField(max_length=50, verbose_name="Region") country = models.CharField(max_length=50, verbose_name="Country") def __unicode__(self): return str( self.country ) class DefaultDBRouter(object): """ A router to control all database operations on models in the auth application. """ def db_for_read(self, model, **hints): """ Reads go to a default. """ return "default" def db_for_write(self, model, **hints): """ Writes always go to default. """ return 'default' def allow_relation(self, obj1, obj2, **hints): """ Relations between objects are allowed if both objects are in the default. """ db_list = ('default') if obj1._state.db in db_list and obj2._state.db in db_list: return True return None def allow_migrate(self, db, app_label, model=None, **hints): """ All non-micro-management models end up in this pool. """ return True models.py - test app - I want to use … -
Is possible to monitor a celery task in a django view without block the server
I have a long running task that I need to decouple from my normal django app. Is called from several clients, and wonder if is possible to give them the ilusion of a synchronous call, where the server take the job of monitor the job and return back when it finish. This mean, that I only need to offload the server and not need to worry about blocking the clients (this is already solved). @task def sync(): # A long process here... So, in my view is possible to do something like: def sync_database(request): while timeout(60): #Monitor task, if error or result: sleep(1) return sync.result without kill the performance? -
Why a call to a celery task block forever?
I follow the tutorial at http://docs.celeryproject.org/en/master/django/first-steps-with-django.html from __future__ import absolute_import, unicode_literals import os from celery import Celery # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'cobros.settings') app = Celery('cobros') # Using a string here means the worker doesn't have to serialize # the configuration object to child processes. # - namespace='CELERY' means all celery-related configuration keys # should have a `CELERY_` prefix. app.config_from_object('django.conf:settings', namespace='CELERY') # Load task modules from all registered Django app configs. app.autodiscover_tasks() # Settings CELERY_APP="cobros" CELERY_BROKER_URL = 'redis://localhost:6379/0' CELERY_RESULT_BACKEND = 'redis://localhost:6379' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_TIMEZONE = TIME_ZONE and call my first job: @task def add(x, y): logger.info("Sum ", x, y) return x + y def syncClientAsync(): baseDir = getBaseDir(str(cobrador.id)) print("Delay...") return add.delay(4, 4) #No work return add.delay(4, 4).get(timeout=1) #No work When I run the code python get stuck/blocked forever. Redis and Celery are running and not report any error or problem. -
Queryset contentype show fields name and values in template table
I got a view that receives a model and field the user passes via post (existing model and field inside the app of course) and makes a queryset filter on it, then i need to show in my template that result in a table (name fields must be the column headers) and their respective values. This what i got so far trying to serialize the queryset result in order to make it easier to show in template: Views.py: from django.contrib.contenttypes.models import ContentType class CommitteeReport(BaseView): template_name = 'committee/committee_report.html' def post(self, request, **kwargs): myfield = request.POST['field'].lower() my_model = request.POST['model'].lower() queryset_obj = ContentType.objects.get(model = my_model).model_class().objects.filter(**{myfield:True}) return render(request, self.template_name,{ 'requirements': queryset_obj, }) And my template: <div class="tab-pane active" id="tab_1"> <table class="datatable table table-striped table-hover" cellspacing="0"> <thead> <tr> {% for key in requirements %} <th>{{ key.fields }}</th> {% endfor %} </tr> </thead> <tbody> {% for item in requirements %} <tr>{{ item.value }}</tr> {% endfor %} </tbody> </table> </div> Thing is, i don't get result or if i change the tag inside the termplate, i get the objects dictionary for every row. Any idea of how to achieve what i need ?, thanks in advance.