Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to properly display all inline fields associated with its parent model fields when paginating in Django template?
I'm a student and a Django newbie, and we have a project that we're trying to build using Django. In my journey to building the project I stumbled upon a problem and got stuck for weeks now. I want to display all the inline fields associated with its parent field on one page as I paginate. When I tried to paginate a model with 2 additional models that have foreign keys to it I got a weird result in my template. I can't seem to figure out how to fix it. I tried several methods on the Internet and have read numerous forums and discussions but to no avail, none has worked so far. Below are my files and a few Images: (models.py) from django.db import models class History(models.Model): BARANGAY = ( ('Alegria','Alegria'), ('Bagacay','Bagacay'), ('Baluntay','Baluntay'), ('Datal Anggas','Datal Anggas'), ('Domolok','Domolok'), ('Kawas','Kawas'), ('Ladol','Ladol'), ('Maribulan','Maribulan'), ('Pag-Asa','Pag-Asa'), ('Paraiso','Paraiso'), ('Poblacion','Poblacion'), ('Spring','Spring'), ('Tokawal','Tokawal') ) barangay_name = models.CharField(max_length=100,choices=BARANGAY,default='Alegria') barangay_img = models.ImageField(upload_to='history_imgs',blank=True) barangay_info = models.TextField() class GeoHazard(models.Model): history = models.ForeignKey(History,related_name='geohazards',on_delete=models.CASCADE) geohazard_img = models.ImageField(upload_to='history_imgs',blank=True) date_published = models.CharField(max_length=100, null=True) geohazard_info = models.TextField() class Assessment(models.Model): RATINGS = ( ('HIGH','HIGH'), ('HIGH (Mitigated)','HIGH (Mitigated)'), ('MODERATE','MODERATE'), ('MODERATE (Mitigated)','MODERATE (Mitigated)'), ('LOW','LOW'), ('UNKNOWN','UNKNOWN'), ) history = models.ForeignKey(History,related_name='assessment',on_delete=models.CASCADE) purok_name = models.CharField(max_length=50) purok_coordinates = models.CharField(max_length=100,default='unknown') flood_rating = models.CharField(max_length=100,choices=RATINGS,default='UNKNOWN') … -
How to get variable from POST method in Modelchoicefield
#forms class ChoiceAddressForm(forms.Form): choice_address = forms.ModelChoiceField(queryset=Address.objects.none(), empty_label='') #views def packing_create(request): if request.method == 'POST': choice_address_form = ChoiceAddressForm(request.POST) choice_address = choice_address_form.fields['choice_address'] return render(request, 'shop/packingcreate.html', {'choice_address': choice_address}) address = Address.objects.filter(usr_adr=request.user).values('adr_no', 'custom_name').order_by('adr_no') address = [tuple(i.values()) for i in address] choice_address_form = ChoiceAddressForm() choice_address_form.fields['choice_address'].choices = address return render(request, 'shop/packingcreate.html', {'choice_address_form': choice_address_form}) This is what I get: <django.forms.models.ModelChoiceField object at 0x7f1f2e6e1460> Also is_valid and cleaned_date not working. -
How to pass "self" or Page.id to a custom admin Panel in the Wagtail CMS?
More generally speaking I want add a custom admin Panel to list some related content. To lookup this related content I need to pass the current instance of the model or at least its ID to this panel. How can I do that within these lists in which these admin panels are noted? Here is my specific example of an ArtistPage. In the editor I would like to add a panel to list WorkPages that are related to this ArtistPage: from wagtail.models import Page class ArtistPage(Page): # ... content_panels = [ # ... ListWorksPanel(artist=self), # This doesn’t work ] The panel itself is defined like that, mostly copied from the HelpPanel: from wagtail.admin.panels import Panel class ListWorksPanel(Panel): def __init__(self, artist="", template="admin/list_works_panel.html", **kwargs,): super().__init__(**kwargs) self.artist = artist self.template = template def clone_kwargs(self): kwargs = super().clone_kwargs() del kwargs["help_text"] kwargs.update( artist=self.artist, template=self.template, ) return kwargs class BoundPanel(Panel.BoundPanel): def __init__(self, panel, instance, request, form): super().__init__(panel, instance, request, form) self.template_name = self.panel.template self.artist = self.panel.artist This is more a general Python question, I think. I know how to pass "self" in functions. But how does that work here with this class as element of a list? I reckon that the __init__() method of the ArtistPage … -
Database content doesn show on production
I am struggling to understand what is missing on my application, sorry it seems a little silly question, I am sure is something quite simple that I am not actually looking to. I have created an API, using REST-FRAMEWORK on my machine and upload it to production, but the content of my database didn't come through. If you see in the picture the product list appers as empty But on my machine it actually has some information -
Ajax post request fails without showing an error, it just prints an empty error
I am trying to create An ajax request in the Django template .. it fails and returns an empty error so am not even able to debug it. Here is what I tried to do : HTML template ..... kml_layer.addListener('click', (kmlEvent) => { setMapOnAll(null); var clickedPoint = kmlEvent.latLng; newPoint.postMessage(clickedPoint.lat() + "," + clickedPoint.lng()); $.ajax({ type: "POST", url: "https://www.{{domain}}{% url 'get_km_from_source' %}", data: { csrfmiddlewaretoken: '{% csrf_token %}', layer_id: "{{ single_layer.id }}", the_element_string_id: kmlEvent.featureData.id, clicked_lat: kmlEvent.latLng.lat, clicked_lng: kmlEvent.latLng.lng }, /* Passing the text data */ success: function (response) { alert("Thankyou for reaching us out " + response); }, error: function (jqXHR, textStatus, errorThrown) { // alert the error if any error occured console.log(textStatus, errorThrown); } }); }); ..... And here is the URL that is being called. path('get_km_from_source/', get_km_from_source, name='get_km_from_source'), Using print debugging in the python function that is being called.. it never reaches this point. but it always fails before starting the request .. and it returns an empty based on the lin console.log(textStatus, errorThrown); .. here is how the error looks like : console output: "error " -
Django Rest Framework: while using generics APIview I'm not able to set permissions
I want the admin user to access every user detail and the non-admin user to get access to its own detail only but Instead of this non-admin user is showing the full list of every user same as the admin user while implementing this. As I've shared my views.py, permissions.py, and models.py for the same. I'm not sure whether the problem is in permisions.py or models.py as I'm new to Django. I'm using Postman for API testing and this is working fine for the admin user but for an individual user, it's not working. views.py class UserListCreateAPIView(generics.ListCreateAPIView): permission_classes = [IsStaffOrTargetUser] queryset = User.objects.all() serializer_class = UserSerializer class UserRetrtieveUpdateDestroyAPIView(generics.RetrieveUpdateDestroyAPIView): permission_classes = [IsStaffOrTargetUser] queryset = User.objects.all() serializer_class = UserSerializer permissions.py class IsStaffOrTargetUser(BasePermission): def has_permission(self, request, view): # allow user to list all users if logged in user is staff return request.user or request.user.is_staff def has_object_permission(self, request, view, obj): # allow logged in user to view own details, allows staff to view all records return request.user.is_staff or obj == request.user models.py class User(AbstractBaseUser): email = models.EmailField(verbose_name='Email',max_length=255,unique=True) name = models.CharField(max_length=200) contact_number= models.IntegerField() gender = models.IntegerField(choices=GENDER_CHOICES) address= models.CharField(max_length=100) state=models.CharField(max_length=100) city=models.CharField(max_length=100) country=models.CharField(max_length=100) pincode= models.IntegerField() dob = models.DateField(null= True) # is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_admin … -
Adding a range price filter
I'm trying to add a range price filter for a list of products with django and I'm having some trouble with how to proceed Here's the code for the template : ( produits.html ) <div class="mb-4"> <h3 class="mb-3 h6 text-uppercase text-black d-block">Filter by Price</h3> <div id="slider-range" class="border-primary"></div> <input type="text" name="PRICE" id="amount" class="form-control border-0 pl-0 bg-white" disabled="" /> Here's the model code for products : class Product(models.Model): nom = models.CharField(max_length=200,null= True, blank=True) prix = models.DecimalField(max_digits=7,decimal_places=2,null=True,blank=True) description = models.TextField(null=True,blank=True) nbr_stock = models.IntegerField(null=True,blank=True,default=0) image= models.ImageField(null=True,blank=True) taille= models.CharField(max_length=5,null=True,blank=True) categorie=models.CharField(max_length=200,null= True, blank=True) @property def imageURL(self): try : url = self.image.url except : url = '' return url def __str__(self): return self.nom My question is how can I "retrieve" the value from the range slider and then show the products according to the price? thank you in advance -
Field 'id' expected a number but got 'category.id'
I'm trying to make a category in the DB, but when I try to access the category with the model that entered. it showing me this Error: ValueError at /category/Django/ Django is category I entered with the model I made using a ForeignKey. I tried a different method for the category but it didn't work either. so I think the problem is in the db.sqlite3 file or in the migrations files. I can't delete the sql3 db file, I have data that I can't easy replaces. I don't think the problem is in the settings.py, I tried to change it before and got the same outcome. the full Error: \Python39\site-packages\django\db\models\lookups.py", line 25, in __init__ self.rhs = self.get_prep_lookup() File "C:\Users\HPi5\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\django\db\models\fields\related_lookups.py", line 117, in get_prep_lookup self.rhs = target_field.get_prep_value(self.rhs) File "C:\Users\HPi5\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\django\db\models\fields\__init__.py", line 1825, in get_prep_value raise e.__class__( ValueError: Field 'id' expected a number but got 'published'. here is the views.py for the category class CatListView(ListView): template_name = "Blog/category.html" context_object_name = 'catlist' def get_queryset(self): content = { 'cat': self.kwargs['category'], 'posts': Post.objects.filter(category__name=self.kwargs['category']).filter(category='published') } return content def category_list(request): category_list = Category.objects.exclude(name='default') context = { "category_list": category_list, } the urls.py from django.urls import path from . import views urlpatterns = [ path("category/<category>/", views.CatListView.as_view(), name="category"), ] and for … -
saving the data with user logout signal
I am using the logout signal for saving the logout time of user as follows class StaffLogData(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='staff_log_data', on_delete=models.CASCADE) log_in_time = models.DateTimeField(verbose_name='Log In Time', blank=True, null=True) log_out_time = models.DateTimeField(verbose_name='Log Out Time', blank=True, null=True) active_time = models.DateTimeField(verbose_name='Active Time', blank=True, null=True) active_log_time = models.TimeField(verbose_name='Active Log Time', blank=True, null=True) timestamp = models.DateTimeField(verbose_name='Timestamp', default=timezone.now) def duration(self): if self.log_out_time: return self.log_out_time.replace(microsecond=0) - self.log_in_time.replace(microsecond=0) else: return None def staff_log_in_data(sender, user, **kwargs): if user: StaffLogData.objects.create(user=user, log_in_time=timezone.now()) user_logged_in.connect(staff_log_in_data) def staff_log_out_data(sender, user, **kwargs): last_log_data = StaffLogData.objects.filter(user=user).last() if last_log_data: last_log_data.log_out_time = timezone.now() print('last logout', last_log_data.log_out_time) last_log_data.save() user_logged_out.connect(staff_log_out_data) It prints the output but not saving it, any help is appreciated. -
django debug toolbar problem with the failed to load module script
I have been installing djang-debug-toolbar, but it is not showing but in the chrome developer console, it shows following error. Failed to load module script: Expected a JavaScript module script but the server responded with a MIME type of "text/plain". Strict MIME type checking is enforced for module scripts per HTML spec. I have installed pip django debug toolbar using pip in pycharm I have changed the setting in the settings.py Also I have changed the urls.py in the project folder I went in the registry of the windows to check on the HKEY_CLASSES_ROOT\.js\Content Type from text/plain to but there is no Content Type folder under the folder .js Any hints? -
How can I create a basic Soap server with spyne in django
I want to create a server which uses Django and make and take response as SOAP, so I try to use spyne for this reason but I can't run the given code class HelloWorldService(ServiceBase): @rpc(Unicode, Integer, _returns=Iterable(Unicode)) def say_hello(ctx, name, times): """Docstrings for service methods appear as documentation in the wsdl. <b>What fun!</b> @param name the name to say hello to @param times the number of times to say hello @return the completed array """ for i in range(times): yield u'Hello, %s' % name application = Application([HelloWorldService], 'spyne.examples.hello.soap', in_protocol=Soap11(validator='lxml'), out_protocol=Soap11()) wsgi_application = WsgiApplication(application) if __name__ == '__main__': import logging from wsgiref.simple_server import make_server logging.basicConfig(level=logging.DEBUG) logging.getLogger('spyne.protocol.xml').setLevel(logging.DEBUG) logging.info("listening to http://127.0.0.1:8000") logging.info("wsdl is at: http://localhost:8000/?wsdl") server = make_server('127.0.0.1', 8000, wsgi_application) server.serve_forever() -
pass a value from bootstrap to django modal
Here i am trying to pass the value outside for loop modal using ajax here is my template.html {% for compliance in compliance %} {% complience_category compliance request.user as compliances %} {% for qualification in compliances %} ..... ..... <td> <button data-id="{{ qualification.id }}" type="button" class="btn btn-warning margin-bottom edit-qualification"> edit </button> </td> .... ..... {% endfor %} {% csrf_token %} <div class="modal hid fade" id="modal-default"> <form class="form-horizontal" method="POST" enctype="multipart/form-data" action=" {% url 'update_qualifications' qualification.id %}"> {% csrf_token %} <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button> <h3>Update Compliance</h3> </div> <div class="modal-body"> <div class="control-group"> <label class="control-label" for="inputdate_{{qualification.id}}">Expiry Date</label> <div class="controls"> <input type="date" id="inputdate_{{qualification.id}}" name="expiry_date" value="{{qualification.expiry_date|date:'Y-m-d'}}"> </div> </div> </div> <div class="modal-footer"> <button class="btn" data-dismiss="modal">Close</button> <button class="btn btn-primary" type="submit">Save</button> </div> </form> </div> {% endfor %} This is my AJAX $(document).on('click','.edit-qualification',function(){ var id = $(this).data('id'); $.ajax({ url:'', type:'POST', data:{ 'id':id, 'csrfmiddlewaretoken': $('input[name=csrfmiddlewaretoken]').val(), }, success:function(data){ $('#edit_modal .modal-dialog').html($('#edit_modal .modal-dialog',data)); $('#edit_modal').modal('show'); }, error:function(){ console.log('error') }, }); }); </script> Here my modal is outside of for loop Here my problem is when i click the edit button my modal popup is not working (it means when clicking the edit button nothing works for me ) -
how to transfer list from django view to django forms?
I have AppointmentCreateView, which performs the function of booking, and I have hours(), which returns a list of hours the worker has received from his individual schedule, i need to return this list to forms class AppointmentCreateView(CreateView): model = Appointment form_class = AppointmentForm template_name = 'appointment/booking.html' success_url = reverse_lazy('workers') def hours(self, pk): worker = User.objects.get(id=pk) schedule = Schedule.objects.get(id=worker.id) HOUR_CHOICES = [] from_hour = schedule.from_hour to_hour = schedule.to_hour while from_hour <= to_hour: HOUR_CHOICES.append(from_hour) from_hour = time(from_hour.hour + 1, from_hour.minute) return HOUR_CHOICES def form_valid(self, form): form.instance.worker = User.objects.get(pk=self.kwargs['pk']) return super(AppointmentCreateView, self).form_valid(form) i need the user to select the desired time from the list but i don't know how to transfer transfer this list here class AppointmentForm(forms.ModelForm): time = forms.TimeField(widget=forms.Select(choices=HOUR_CHOICES)) class Meta: model = Appointment fields = ('location', 'time') def __init__(self, *args, **kwargs): super(AppointmentForm, self).__init__(*args, **kwargs) self.fields['location'].empty_label = 'Select' -
Wie kann ich meiner Web Anwendung sagen, dass sie auf gespeicherte Datei zugreifen und diese ausgeben soll? [closed]
Ich stehe vor folgendem Problem und hoffe ihr könnt mir weiterhelfen: Für meine Arbeit muss ich Daten aus einer Website auf meine eigenentwickelten Webanwendung exportieren und anhand dieser Daten ein Gantt Diagramm zeichnen. Für das Exportieren gibt es schon eine Funktion auf der Website. Die Daten können als html Datei oder XML Datei exportiert werden. Doch wie sag ich meiner Web Anwendung, dass diese auf die gespeicherten Daten zugreifen und auslesen soll? Auf was muss ich hierbei achten? Ist JS dafür eine geeignete Sprache oder empfehlt ihr mir mit einer anderen Programmiersprache zu arbeiten wie z.B Python? Oder sogar vllt. dass Framework Django nutzen? Ich bin für jeden Tipp dankbar! Lg -
Setting callback domain in django allauth
I have fargate containers , the one has django and the other has nginx. And django use allauth for login. https://django-allauth.readthedocs.io/en/latest/installation.html In this case, when accessing OAuth allauth makes the callback url such as, 127.0.0.1/callback/something However, Of course it doesn't work. Callback url should be example.com/callback/something. How can I set the callback domain? -
AttributeError at / 'AnonymousUser' object has no attribute '_meta'
I was trying to use signin page but this error shows up. Image of error while running in Mozilla web browser localhost I had tried the solution using this link and ended up mixing auth model to the chatbot model. this is the link of my whole views.py file of chatbot app. https://pastebin.com/2E7mgyuR def get(self, request): return render(request, 'chatbot/signin.html') def post(self, request): context = { 'data': request.POST, 'has_error': False } username = request.POST.get('username') password = request.POST.get('pass1') if username == '': messages.add_message(request, messages.ERROR, 'Username is required') context['has_error'] = True if password == '': messages.add_message(request, messages.ERROR, 'Password is required') context['has_error'] = True user = authenticate(request, username=username, password=password) # if not user and not context['has_error']: # messages.add_message(request, messages.ERROR, 'Invalid login') # context['has_error'] = True if context['has_error']: return render(request, 'chatbot/signin.html', status=401, context=context) login(request, user) return redirect('chatpage') and This is my models.py of chatbot from django.db import models from django.contrib.auth import get_user_model # Create your models here. Mod = get_user_model() class User(Mod): is_email_verified = models.BooleanField(default=False) def __str__(self): return self.email and this is what it is showing in terminal Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). June 27, 2022 - 09:27:56 Django version 4.0.5, using settings 'Eva_Chatbot.settings' … -
category and paginator connections django html
I have a problem when I select one category and in this category when I want to go to another page it sends me just to a different page and I need it to send me to for example category=pk {{ page=2 }} or like this but now it sends to {{ page=2}} enter image description here -
How to Get queryset not dict django aggregate
i'm using this queryset for my requirements invoices = Invoice.objects.aggregate(total_amount=Sum('order__order_items__amount'),number_of_invoices=Count('pk', distinct=True)) which returns dict---> {'total_amount': Decimal('17700.00'), 'number_of_invoices': 2} but I want queryset how can i do that.. Thanks for any help -
Django differentiate between fetch requests
I have 2 different fetch request coming to the same view in Django. How do I differentiate between them? The first fetch request is loading new content and the second is used for a different purpose altogether but they both come from the same url and to the same view. I have the following code in my view: if request.headers.get('X-Requested-With') == 'XMLHttpRequest': return async_response(request, post) And what I need is something similar to: if request.headers.get('X-Requested-With') == 'XMLHttpRequest': if fetch function 1: django function 1 if fetch function 2: django function 2 Do i need to add some custom headers? -
No such file or directory when python manage.py runserver
I have function to upload the document in folder, after it i want to execute methods to transform this file. I wrote another functions where i am calling this methods, but after pyrhon manage.py runserver i receive No such file or directory: 'beeline/media/docs/assignment.xlsx' But if i execute python file with methods everyrhing is working fine class UploadView(generic.TemplateView): def get(self, request): form = ExcelForm return render(request, 'index.html', {'form': form}) def injection(self): post_team() post_db_service() post_database() post_db_schema() post_db_table() return "Everything is created" def post(self, request): if request.method == 'POST': form = ExcelForm(request.POST, request.FILES) if form.is_valid(): upload = request.FILES['file'] fss = FileSystemStorage('media/docs') fss.save(upload.name, upload) self.injection() return render(request, 'ty.html') return render(request, 'index.html') -
Django calculated fields on custom queryset
This seems like a basic question but for the life of me I cannot seem to figure this out. I have a Recipe model that uses a custom RecipeQueryset as a manager. Now I've been doing a lot of reading on where to put business logic of the application some people suggest a "services" layer others say to put it in a custom queryset which is what I am trying to accomplish now. None of them really give an example of doing calculations though only CRUD functionality. At the moment I have a property of total_cost defined on the Recipe model but according to a lot of articles/discussions I should be moving this "business logic" to elsewhere to the custom queryset for example? Is there a way to do the calculation in a custom queryset method for a queryset of Recipe objects and calculate that total_cost for each Recipe and return that queryset with the extra total_cost field? How would I then add this so it can be used in my serializer? Model class RecipeQueryset(models.QuerySet): """Custom queryset for Recipe Model""" def all_for_user(self, user): return self.filter(user=user) # this is where I think I should put it? def total_cost(self, recipe): return # … -
While downloading xls file from django download code, file is not opening, It shows corrupted
Here is my code for xls download using python(Django) views.py def downloadfile(request, filename=''): if filename != '': BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) filename = 'SampleExcel.xls' filepath = BASE_DIR + "\SampleExcel\SampleExcel.xls" path = open(filepath, encoding='cp437') mime_type, _ = mimetypes.guess_type(filepath) response = HttpResponse(path, content_type=mime_type) response['Content-Disposition'] = "attachment; filename=%s" % filename return response else: return HttpResponseRedirect("adduser", {}) With this code I am able to download file properly, but while opening that file it shows me error. I attach screenshot of error. I have tried this code for solution, if filename != '': BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) filename = 'SampleExcel.xls' filepath = BASE_DIR + "\SampleExcel\SampleExcel.xls" return FileResponse(open(filepath, 'rb') , True, filename) else: return HttpResponseRedirect("adduser", {}) This also not works, It shows error 'TypeError at /downloadfile/SampleExcel.xls HTTP status code must be an integer.', and it is not even downloading. Please help me. I am stuck here from last 3 days. Note: I need to download xls file only, as after downloading it I have to perform import functionality with that downloaded xls file. I can not change xls to xlsx. -
Django Form Is None
Im on investigation Django framework and now trying to create custom procedure of resetting password. I use this URL path path('password_reset_confirm/<uidb64>/<token>', PasswordResetConfirmView.as_view( template_name='user_account/reset_password/password_reset_confirm.html', success_url='/account/password_reset_complete/'), name="password_reset_confirm"), In template i use crispy form <form class="login-form p-4 rounded" method="post"> {% csrf_token %} <h1 class="h4 mb-4 font-weight-bold">Change your password</h1> <p>Use the form below to change your password.</p> {{ form|crispy }} <button type="submit" value="Change"> Submit </button> </form> So now this form do not showing in template, and if if type {{ form }} instead of {{ form.as_p }} or crispy form, that showing me None in form place. -
"GET /static/css/stylesheet.css HTTP/1.1" 404 1813
I tried to ling CSS file in Django framework by using " " It shows error but, it is showing error ""GET /static/css/stylesheet.css HTTP/1.1" 404 1813file Oder" -
Can't use context data in the HTML in django
models.py class ChapterQuestions(models.Model): question_id = CharField(primary_key=True, max_length=40) question_order = CharField(max_length=40, blank=True, null=True) question_wording = CharField(max_length=4000, blank=True, null=True) question_type = CharField(max_length=1, blank=True, null=True) sub_question = CharField(max_length=1, blank=True, null=True, default='N') sub_question_trigger = CharField(max_length=1, blank=True, null=True, default='Y') answer_required = CharField(max_length=1, blank=True, null=True, default='Y') parent_question = models.ForeignKey('self', on_delete=models.DO_NOTHING) chapter = models.ForeignKey(ReportChapter, on_delete=models.DO_NOTHING) update_date = models.DateField(blank=True, null=True) update_user = models.ForeignKey(User, on_delete=models.DO_NOTHING, db_column="update_user", blank=True, null=True) class Meta: managed = True db_table = "Chapter_Question" views.py class LfrReportChapterOneView(PermissionRequiredMixin, TemplateView): permission_required = "RockHub_App.is_in_risk_and_ic_team" template_name = "../templates/dashboards/lfr/lfr_report_chapitre1_create.html" def get_context_data(self, *args, **kwargs): context = super(LfrReportChapterOneView, self).get_context_data(*args, **kwargs) data = ChapterQuestions.objects.filter(chapter_id=1).order_by("question_id") context["questions"] = data return context While debugging i can see all the data available in the database but in the HTML file when I write **<h1>{{ questions.question_id }}</h1>** or <div hidden> {% for qst in questions %} {{ qst.question_id }},{{ qst.question_name }} {% endfor %}</div> <div><h1>{{ qst.question_id }}</h1></div> Nothing is shown !!