Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Passing a placeholder text using django-filter and different views
I have a model: class Movie (models.Model): category = models.CharField(max_length=50, verbose_name='Kategoria filmu', default= 'unassigned', null=False, choices=category_choices) source = models.CharField(max_length=50, verbose_name='Źródło filmu', default= 'unassigned', null=False, choices=source_choices) promotion = models.BooleanField(default=False, verbose_name='PROMOCJA FILMU') author = models.CharField(max_length=50, verbose_name='Nazwa influencera') title = models.CharField(max_length=50, verbose_name='Nazwa filmu') content = models.TextField(max_length=10000, verbose_name='HTML EMBEDED do filmu') date_posted = models.DateTimeField(default=timezone.now) youtube_url = models.URLField(blank=True, max_length=300) tiktok_url = models.URLField(blank=True, max_length=300) insta_url = models.URLField(blank=True, max_length=300) I am passing it to the view with djnago-filter with different category choice: views.py: #HotTop View class HotTopView (FilterView): model = Movie template_name = 'pages/hot_top.html' filterset_class = MovieFilter paginate_by = 6 def get_queryset(self): category_qs = self.model.objects.filter(category="HOT-TOP") return category_qs.order_by('-date_posted') #Odkrycia View class OdkryciaView (FilterView): model = Movie template_name = 'pages/odkrycia.html' filterset_class = MovieFilter paginate_by = 6 def get_queryset(self): category_qs = self.model.objects.filter(category="ODKRYCIA") return category_qs.order_by('-date_posted') and my filters.py: class MovieFilter(django_filters.FilterSet): author = django_filters.CharFilter(label='', lookup_expr='contains', widget=TextInput(attrs={'placeholder': 'Search'})) class Meta: model = Movie fields = ['author'] The question is how can i change placeholder of my serach form depending on the view (HotTop or Odkrycia). I want it to be - when i am in HotTop View -> Search in Hot Top and when i am in Odkrycia - > Search in Odkrycia -
Django back end to serve a react front end images
I am working in a project with a django back and a react front. I am stuck on displaying images on react front. The url served in my react console is : http://localhost:8000/media/media/images/cards/card1.jpg When I load this url in a new chrome the page the image is displayed however in my react page the image is blank. Here are my django settings.py : # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent #Directories PROJECT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) MEDIA_ROOT = os.path.join(BASE_DIR) MEDIA_URL = '/media/' Here is my serializer : class StartupSerializer(serializers.ModelSerializer): class Meta: model = Startup fields = ('id', 'header', 'title', 'category', 'description', 'tags' , 'card_image' , 'logo_image') And here is my model : class Startup(models.Model): header = models.CharField("Header", max_length=255, null=False) title = models.CharField("Title", max_length=255, null=False) category = models.CharField("category", max_length=255, null=False) description = models.CharField("description", max_length=255, null=False) # TODO Change this to options instead of array tags = ArrayField(models.CharField(max_length=10, blank=True), size=5,) # TODO Images to be stored in aws only url will be in DB card_image = models.ImageField(upload_to='media/images/cards', null=False) logo_image = models.ImageField(upload_to='media/images/logos', null=False) createdAt = models.DateTimeField("Created At", auto_now_add=True) def __str__(self): return self.title Please not on recat side the axios works fine and I can get all other fields … -
How can I find out the type by accessing the column of the index of the models.all() result?
How can I find out the type by accessing the column of the index of the models.all() result?? My code is like this: def qtj(result_model): for index in result_model: print('index : ', index) for column in index: print(f'column : {column} type:{type(column)}') but this at index : index : {'board_seq': Decimal('15'), 'board_title': '제목', 'board_content': '내용', 'board_writer': '무명', 'board_password': '1234', 'create_date': datetime.datetime(2021, 11, 27, 18, 6, 8, 586137)} and in the column : column : board_seq type:<class 'str'> What I want to do is find the datetime.datetime, not the str. -
How to avoid Django shows multiple logs in shell
I have a part of codes like below in Django project. This code gives the same multiple logs in the shell. si_ids = Blank_Form.objects.get(blank_form_id__exact=blank_form_id).core_service_id.split('s')[1::] logger.log(20, '[si_ids] {}'.format(si_ids)) [si_ids] ['49', '69', '50', '56'] [si_ids] ['49', '69', '50', '56'] ... about 10 same line continues Every line that has logger.log gives the same 10 more lines. How to get just a single line of log? -
ValidationError with Custom pagination in ListAPIView
I am trying to set error message in my ListAPiview where if a user tries to access data other than Pool Operator he should get a permisiion denied error Views.py class ProductListAPIView(generics.ListAPIView): serializer_class = ProductSerializer pagination_class = StandardResultsSetPagination permission_classes = (permissions.IsAuthenticated, ) def get_queryset(self): company = self.request.GET['company'] view = self.request.GET['view'] if view=='Pool Operator': emp = list(Employee.objects.filter(company=company).values_list('pk', flat=True)) queryset = Product.objects.filter(owner__in=emp).order_by('-pk') return queryset else: return ValidationError( {'permission denied': "Can't see user's Products"} ) But when I run this I get the following error: object of type 'ValidationError' has no len() What needs to be changed to show a successful error message? -
Use variable as form fields in Django form template
<here all loading of static , template_filters, crispy_forms > <form> {% for i in artifact_length %} {% with artifact_name="artifact_"|artifact_name:forloop.counter0 %} {{form.artifact_name|as_crispy_field}} {% endwith %} {%endfor%} </form> This is related template code. Here i want to render form fields with names artifact_0, artifact_1 as coming from form. The variable artifact_name inside with is working fine and returning expected identifiers artifact_0 , artifact_1, but i want to use these variables as form fields to render as as_crispy_field. The code {{form.artifact_name|as_crispy_field}} does not print anything because it is assuming form as field with name artifact_name which is not. Instead i want to use the value of variable here. forms.py class Someform(forms.form): def __init__(self, artifact_obj): super().__init__() count = 0 for artifact in artifact_obj: self.fields[f'artifact_{count}'] = forms.CharField(widget=forms.NumberInput()) count += 1 tags.py @register.filter('artifact_name') def get_artifact_name(artifact_prefix: str, counter: int): print('method', 'prefix', artifact_prefix, 'counter', counter) return f'{artifact_prefix}_{counter}' There is variable length form being created. As informs.py form fields are being created with artifact_count where count can range from 0 to len of obj. -
How to apply filter based on dates of an already existing database with Django Queryset
So i have the below's QuerySet output : <QuerySet [{'price': 12.515, 'price_date': datetime.datetime(2017, 3, 13, 0, 0, tzinfo=)}, {'price': 12.335, 'price_date': datetime.datetime(2017, 3, 14, 0, 0, tzinfo=)}, {'price': 12.37, 'price_date': datetime.datetime(2017, 3, 15, 0, 0, tzinfo=)}, {'price': 12.35, 'price_date': datetime.datetime(2017, 3, 16, 0, 0, tzinfo=)}, {'price': 12.305, 'price_date': datetime.datetime(2017, 3, 17, 0, 0, tzinfo=)}... How can i get say the price with price_date = 11-26-21 (November 26th 2021) ? Or if i want to filter by latest 30 prices? Thanks -
VS Code suggestion attribute of Django class based view
vscode django classbased view suggestion Hello Experts, I have been creating djagno project on vscode as per front screen(windows 10) in the picture and vscode helped me to write correct attribute of the class based view with suggesoin (Ex. context_object_name) I have shifted to windows 11 as per the second screen in the back. I am not getting suggesion of the attribute of Djanngo's class based view and I would like to see it there same as front screen in the picture. Can anyone help me with the query? Thanks in advance for ones time and efforts to answer my query. -
Timetable in django
In my django app i would like to create a timetable showing all appointments per day. For example: Time | Seat 1 | Seat 2 | etc 9:00am John Doe Jim Doe 10:00am John Doe Jim Doe Currently i have models for appoint and seat: class Appointment(models.Model): user = models.ForeignKey(Account, on_delete=models.CASCADE) seat = models.ForeignKey(Seat, on_delete=models.SET_NULL, null=True) start_appointment = models.DateTimeField(default=timezone.now, blank=True) end_appointment = models.DateTimeField(default=timezone.now, blank=True) name = models.CharField(max_length=255) date_created = models.DateTimeField(_('Date Created'), auto_now_add=True) date_updated = models.DateTimeField(_('Date Updated'), auto_now=True) class Seat(models.Model): name = models.CharField(max_length=255) slug = models.SlugField() short_description = models.TextField(blank=True, null=True) created_at = models.DateField(auto_now_add=True) Could you please propose a way or steps of how to achieve that? -
How to make a left join query in Django ORM
My models: class Post(models.Model): user = models.ForeignKey(BucketUser, on_delete=models.CASCADE) content = models.ForeignKey(Content, on_delete=models.CASCADE, blank=True, null=True) resource_type = models.CharField(max_length=150) url = models.URLField() text = models.TextField() class Rating(models.Model): user = models.ForeignKey(BucketUser, on_delete=models.CASCADE) content = models.ForeignKey(Content, on_delete=models.CASCADE) rating = models.IntegerField(choices=rating_choices, default='1') The PostgreSQL Tables: posts_post : | id | url | resource_type | text | content_id | user_id | ratings_rating : | id | rating | content_id | user_id | I want to get the contents of posts_post table along with the respective rating values from ratings_rating for the same content_id and a user_id which I'll receive from the GET request. I can get that easily by SQL query like: SELECT p.*, r.rating FROM posts_post p LEFT JOIN ratings_rating r ON p.content_id = r.content_id AND r.user_id = 100; /* Assuming user_id received was 100 */ or i can even do this: SELECT p.*, (SELECT r.rating FROM ratings_rating r WHERE r.content_id = p.content_id AND r.user_id = 100) AS rating FROM posts_post p; But, I'm troubled about how to do the same through Django ORM queries based on the models. Or, if I need to create new models for this? What would be the Django way of doing it? I'm still new with Django models, and … -
Django data is not rendering as saved in model
I'm uploading data to one of the models using CSV file. There is no issue in saving the data. It is getting saved as needed. But just after uploading the data all the foregin key value rendering same. In the above image all data is same. But on restarting the server using python manager.py runserver. The value are rendering as expected. Function used in rendering the data. There is no effect of refreshing it. It starts rendering the correct data on performing python manage.py runserver -
how to model formset in modal form - django
i'm trying to implement two formset in one view , one of the formsets should be pop up modal form : here is the models class MobileCollection(models.Model): mobile = models.ForeignKey(ModelCategory,on_delete=models.PROTECT,related_name='model_category') qnt = models.IntegerField() price = models.DecimalField(decimal_places=3,max_digits=20) class Imei(models.Model): mobile = models.ForeignKey(MobileCollection,on_delete=models.PROTECT) imei = models.CharField(max_length=15,unique=True) serial_no = models.CharField(max_length=7,unique=True,blank=True,null=True) status = models.BooleanField(default=True) def __str__(self): return f'{self.mobile}-{self.imei}' if quantity = 10 then we have 10 unique imei , for each mobile item we have multiple imei , the im ei should be inserted in a pop up modal @login_required def create_collection(request): item_formset = mcollection(queryset=MobileCollection.objects.none()) imei_formset = imei_modelformset(queryset=Imei.objects.none()) if request.POST: item_formset = mcollection(request.POST) imei_formset = imei_modelformset(request.POST) if imei_formset.is_valid() and item_formset.is_valid() and request.user.is_superuser: for item in item_formset: item_obj = child.save(commit=False) item_obj.save() for imei in imei_formset: imei_obj = imei.save(commit=False) imei_obj.mobile = item_obj imei_obj.save() return JsonResponse({'success':True}) else: return JsonResponse({ 'success':False,'error_child_msg':item_formset.errors,'error_imei_msg':imei_formset.errors}) context = { 'item_formset':item_formset, 'imei_formset':imei_formset } return render(request,'storage/collection.html',context) but it only saves the last item entry and doesnt save imei , only its instance(from the item) will be saved and here is my formsets mcollection = modelformset_factory( MobileCollection,form=MobileCollectionForm,fields= ['mobile','qnt','price'],can_delete=True,extra=1) imei_modelformset = modelformset_factory(Imei,form=ImeiForm,fields= ['imei'],extra=1,can_delete=True) and here is my html and jquery const addNewRow = document.getElementById('add-more') const totalNewForms = document.getElementById('id_form-TOTAL_FORMS') addNewRow.addEventListener('click',add_new_row); function add_new_row(e){ if(e){ e.preventDefault(); } const currentFormClass = … -
Django Rest Framework Handle a lot of Request & Responses with put method for text editor
I Have a Text Editor in FrontEnd And I want to save text changes as soon as I stop typing but requests and responses are a lot I want to handle this problem with best way Do you know a solotion or package for handling this? thank you -
Trying to get data from data base in django
Trying to get data from database table, i want to show data by when user click on the employee name and it should show data from OverTime table , i have attempted many way to get it dome but none of them worked, please mentor and guide me. models.py class Employee(models.Model): user = models.ForeignKey(User, null = True, on_delete = models.CASCADE) emp_name = models.CharField(max_length = 250, default = '') emp_l_name = models.CharField(max_length = 250, default = '') emp_email = models.EmailField(max_length = 250, default = '') emp_number = models.IntegerField() def __str__(self): return self.emp_name class OverTime(models.Model): emp_user = models.ForeignKey(Employee, null = True, on_delete = models.CASCADE) overTime = models.FloatField( blank = True, null=True) reaion = models.CharField(max_length = 250, blank = True, null=True) date_ot = models.DateTimeField(null = True, blank = True) def __str__(self): return str(self.emp_user) urls.py path('add_Ot/', views.add_Ot, name = 'add_Ot'), path('add_ex/<int:pk>', views.add_Ot, name = 'add_ex'), views.py def add_Ot(request, pk = None): emp = Employee.objects.filter(user=request.user) forms = OverTimeAdd(request.GET) detail_id = Employee.objects.filter(pk = pk) if request.method == "GET": if forms.is_valid(): forms.save() messages.success(request, 'Successfully Over Time added !') contex = { 'emp': emp, 'forms': forms, 'detail_id' : detail_id } return render(request, 'working/html/add_Ot.html', contex) html <tbody> {% for emp in emp %} <tr> <td class="detail"><a href="">{{ emp.id }}</a></td> … -
how to get iterable collection (queryset) from a more than one ManyToManyField field in Django?
I want to get a list of doctors from clinics based on a particular city. I have developed a workaround but it seems expensive operation as I am using a loop to do so. Clinic Model: class Clinic(models.Model): clinic_name = models.CharField(max_length=255) address = models.CharField(max_length=255, null=True, blank=True) doctor = models.ManyToManyField(Doctor, blank=True) city = models.ForeignKey(City, on_delete=models.CASCADE) latitude = models.CharField(max_length=255, null=True, blank=True) longtitude = models.CharField(max_length=255, null=True, blank=True) active = models.BooleanField(default=True) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.clinic_name City Model: class City(models.Model): name = models.CharField(max_length=200) def __str__(self): return self.name Doctor Model: class Doctor(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True, related_name="doctor") speciality = models.ManyToManyField(Speciality, blank=True) service = models.ManyToManyField(Service, blank=True) condition = models.ManyToManyField(Condition, blank=True) def __str__(self): return f"{self.title} {self.user.full_name}" My workaround is: >>> my_city = City.objects.get(name='Kabul') >>> clinics = Clinic.objects.filter(city=city) >>> doctor_list = [] >>> for clinic in clinics: doctor_list.extend(clinic.doctor.all()) >>> doctor_list [<Doctor: Dr. Doctor Khan One>, <Doctor: Prof. Doctor Khan Two>, <Doctor: Dr. Doctor Khan One>, <Doctor: Dr. Doctor Khan One>] >>> the_result = set(doctor_list) >>> new_doctor_list = list(the_result) >>> new_doctor_list [<Doctor: Dr. Doctor Khan One>, <Doctor: Prof. Doctor Khan Two>] -
I am having issue with django web application deployement on ubuntu VPS. The issue is that the server do not give any respnse even on 0.0.0.0:8000
While deploying the Django website everything goes right but when I run the command python manage.py runserver 0.0.0.0:8000 then the server starts successfully but then if I try the IP:8000 on the browser, it shows the site can't be reached and even no computation executes on the server terminal of Django. I have executed sudo ufw allow 8000 but still, the error is the same. I have tried apache and nginx but got the same output for both. I am following this guide https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-18-04 also tried: https://www.codewithharry.com/blogpost/django-deploy-nginx-gunicorn I am using VPS having 1 core, 0.5 GB RAM, Data transfer rate:400 Mbps, I am wondering if Django's requirements for running the application are not met. Kindly Help me solve this problem. It is my 4th day struggling with this error. -
Can I migrate some models dynamically in Django?
I have a few apps, so in each app I have multiple models. Assuming in app X I have models A, B and C, but I want model A to be dynamically migrated. In other words, in a development environment I can migrate or not, depending on some environment variable. I configured managed to get the value from the environment variable, but that only works to generate the migration. I want it to work anytime I'm going to apply the migration. How can I do this? -
Django: NoReverseMatch at
So when I go to the url: http://127.0.0.1:8000/post/2/. instead of showing me the post detail view, it gives me an error. I am so confused about it. However I can see it in list view and in profile page. posts views.py class PostDetailView(LoginRequiredMixin, DetailView): model = Posts template_name = 'posts/detail.html' models.py class Posts(models.Model): caption = models.CharField(max_length=2200) date_posted = models.DateTimeField(default=timezone.now()) image = models.ImageField( upload_to='PostsImages') user = ForeignKey(User, on_delete=models.CASCADE ,related_name='userposts') def __str__(self): return f"Post {self.id} ({self.user.username})'s" def save(self, *args, **kwargs): super().save(*args, **kwargs) img = Image.open(self.image.path) img.save(self.image.path) the main urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('posts.urls')), path('user/', include('users.urls')), path('comments/', include('comments.urls')) ] posts urls.py from django.urls import path from django.conf import settings from django.conf.urls.static import static from .views import PostsListView, PostCreatView, PostDeleteView, PostDetailView urlpatterns = [ path('', PostsListView.as_view(), name='homepage'), path('delete/<int:pk>/', PostDeleteView.as_view(), name='delete-post'), path('creat-post', PostCreatView.as_view(), name='create-post'), path('post/<int:pk>/', PostDetailView.as_view(), name='detail-post') ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) users urls.py from django.urls import path from django.contrib.auth import views as auth_views from .views import ProfileDetailView from .views import SignUp, LogOut urlpatterns = [ path('signup/', SignUp, name='signup'), path('login/', auth_views.LoginView.as_view(template_name='users/login.html'), name='login'), #template_name'xx' tells it where to find the log in url path('logout/', LogOut, name='logout'), path('<int:pk>/profile', ProfileDetailView.as_view(), name='profile') ] -
serving media files in Django for Production
I want to serve all types of media files in my Django Project I used Whitenoise to server static files and static files are working well but I'm having issues with serving images that are uploaded by users (I'm using Linux shared hosting Cpanel) Directory structure Project_name App_1 App_2 Staticfiles (that are collected via collectstatic cmd) manage.py passenger_wsgi.py and here is the project's settings.py STATIC_ROOT = BASE_DIR / 'staticfiles' STATIC_URL = '/static/' MEDIA_URL = '' STATICFILES_DIRS =[ BASE_DIR/ 'static' ] MEDIA_ROOT = BASE_DIR / 'staticfiles/images' and file urls.py urlpatterns+=static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT) -
Uncaught SyntaxError: Unexpected identifier pls help me
I tried to display the message but it won't display This is views def allmessage(request, room): room_details = Room.objects.get(name=room) messages = Message.objects.filter(room=room_details.id) return JsonResponse({"messages":list(messages.values())}) This is display method This link doesn't work /getMessages/{{room}}/ in my terminal $(document).ready(function(){ setInterval(function(){ $.ajax({ type: "GET" url: "/getMessages/{{room}}/", success: function(response){ console.log(response); $("#display").empty(); for (var key in response.messages) { var temp="<div class='chat-box'><b>"+response.messages[key].user+"</b><p>"+response.messages[key].value+"</p><span class='time-left'>"+response.messages[key].date+"</span></div>"; $("#display").append(temp); } }, error: function(response){ alert('There is an error') } }); },1000); }) </script> and also have this problem pls help thank you -
Error when trying to access an item in a for loop
Greetings all I'm trying to get a value if it is equal to a string in looping through items. But I'm getting error "Dictionary entries must contain key/value pairs" and I don't know how to fix that. I'm new to python programming and I'm struggling to find information of how it should be done. I'm using python3.x My code looks like this for index, debtor in enumerate(case.get_debtors): if debtor.type==1: context = { "recipientName": f"{debtor.first_name} {debtor.middle_name} {debtor.last_name}".replace('None', ''), "debtorRole": "Длъжник", "debtorAddress": debtorAddress, "publicExecutorDefaultBankAccount": "ygvyvb", "courtStaff": f"{case_details.systav}".replace('None', ''), "courtName": f"{case_details.courtName}".replace('None', ''), "archNumber": case.id, "debtorName": f"{debtor.first_name} {debtor.middle_name} {debtor.last_name}".replace('None', ''), "creditorName": f"{creditor.first_name} {creditor.middle_name} {creditor.last_name}".replace('None', ''), #creditor.type==2 "creditorAddress": creditorAddress, "executionListDate": executionListDate, "exListIdentifier": exListIdentifier, "amount": amount, "amountDate": amountDate, "agreementInterest": agreementInterest, "penaltyInterest": penaltyInterest, "expences": expences, "taxPublicExecutor": taxPublicExecutor, "brokerage": brokerage, "measuresSum": measuresSum, if debtor(index).postcode1=="1000": "recipientNameNAP": "ТД НА НАП – СОФИЯ", "recipientAddressNAP": "Адрес: ул.„Аксаков” № 21 1000 София", "BASE_DIR": f"{settings.BASE_DIR}".replace("""\\""", "/"), } Please help me. I know it is something simple, but I can't find a solution -
Trouble with Django Channels AllowedHostsOriginValidator
Everytime I use the AllowedHostsoriginValidator I'm unable to get a websocket connection. it immediately handshakes, rejects and disconnects : (where 'my ip' is my ip) WebSocket HANDSHAKING /ws/joingroup/8598969d-3dfa-4017-849c-dcbb71c1f9f0/ [my ip:62745] WebSocket REJECT /ws/joingroup/8598969d-3dfa-4017-849c-dcbb71c1f9f0/ [my ip:62745] WebSocket DISCONNECT /ws/joingroup/8598969d-3dfa-4017-849c-dcbb71c1f9f0/ [my ip:62745] application = ProtocolTypeRouter({ # (http->django views is added by default) "http": get_asgi_application(), 'websocket': AllowedHostsOriginValidator( URLRouter( uppicdoapp.routing.websocket_urlpatterns ) ) , }) my settings.py file i have: ALLOWED_HOSTS = ['127.0.0.1', '10.0.2.2', 'my ip'] now when I remove that allowedhostsoriginvalidator, I am able to connect! Is there something I'm missing for the ALLOWED_HOSTS setting? -
I want find a point in between given points rectangle using python if possible in django
Here in my given points i was tried to match from django query, please help me to best way. y=800.2816162109375 1200, 750 block_list = Block.objects.filter( Q(block_coordinates__topRight__y__gte=y)&Q(block_coordinates__botRight__y__gte=y)& Q(block_coordinates__topLeft__x__gte=x)&Q(block_coordinates__topRight__x__lte=x)& Q(block_coordinates__topLeft__y__lte=y) | Q(block_coordinates__botLeft__y__gte=y) ).values('block_id','block_coordinates') ``` -
Program 'pip.exe' failed to run: The file or directory is corrupted and unreadable
While I was trying to download Django, I got this error that can be found in here. These are some clues for you: Before I downloaded django, I activated the virtual environment but maybe something went wrong with it because I couldn't see anything changed after activating. And one more thing is I'm trying to download Django in my external USB. -
django get id for traverse a list
i want to convert my list into dict to have my id so i try this in my views def img2(request): posts = Post.objects.all() i=[] for p in posts: print(p.id) i.append(p.id) #post={'id':str(p.id)} #print(i) '''def Convert(lst): res_dct = {str(lst[i]): lst[i] for i in range(0, len(lst), 1)} return res_dct # Driver code d=Convert(i)''' d = {str(i[k]): i[k] for k in range(0, len(i), 1)} print(d) for j in d: print(j) return render(request, 'imgg.html', d) then i want to display every id in html and this is my html file: test {% for n in d %} {{n}} {% endfor %} so.. nothing happened and i don't know what's the problem some help plz and thx a lot in general i have a model form post and another one for images with foreignkey and i want to display every post with first image uploded so i have my db with post and images but i never get the first image to display at home page then i try to make a dict with all post_id with for i will try to display every single image_post for her post if u have another method i will be thankfull ^^