Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Local dependency not editable poetry
Just pulled this library to my django project to modify it. Installed it as a local dependency using poetry add ./django-rest-framework-passwordless. The develop mode is set to true. drfpasswordless = {path = "django-rest-framework-passwordless", develop = true} [[package]] name = "drfpasswordless" version = "1.5.8" description = "Passwordless auth for Django Rest Framework Token Authentication." category = "main" optional = false python-versions = ">=3" develop = true Whenever I'm trying to change something (for example urls) urlpatterns = [ path(api_settings.PASSWORDLESS_AUTH_PREFIX + 'emaillllll/', ObtainEmailCallbackToken.as_view(), name='auth_email'), ... ] the state keeps unchanged. Do you know what could be a reason? -
How to connect redis for celery to a django app deployed in digital ocean
I hae recently deployed a django app in digitalocean. My app uses celery and redis for several email sending puposes and scheduled tasks. I have been searching for a documentation on how to connect redis and how to det the celery worker running for my app in digital ocean, but I am unable to find any proper way or documentation. Please can someone tell me how to exactly setup this in digital ocean. -
Images are not displaying in Django production server
I uploaded a few icons to the static/img/ directory in my Django project, which is based on the Django Admin interface. I have one testing server and one production server. Both are using https://fra1.digitaloceanspaces.com to store static project files. To display specific icons, I created custom field in Django ModelAdmin: def get_type(self, obj): return format_html( '<img alt="type" src="{static_url}/img/type_icons/type-{type}.png">', static_url=settings.STATIC_URL, type=obj.type ) project/settings.py When developing locally STATIC_URL = '/collected-static/'. In development and production mode STATIC_URL = '{}/{}/static/'.format(AWS_S3_ENDPOINT_URL, AWS_STORAGE_BUCKET_NAME). AWS_S3_ENDPOINT_URL is https://fra1.digitaloceanspaces.com. AWS_STORAGE_BUCKET_NAME is either project-develop (testing) or project (production). These variables are configured in deployment YAML file. Locally and in development(testing) mode images are displayed perfectly fine this way, but inside production mode images are not displayed at all. I've tried changing the location of the files and even changing the deployment configuration, but nothing seems to help getting the icons to show up in production. /collected-static/img/type-object_type.png (example of icon img src on localhost - OK) https://fra1.digitaloceanspaces.com/project-develop/static/img/type-object_type.png (example of icon img src on testing server - OK) https://fra1.digitaloceanspaces.com/project/static/img/type-object_type.png (example of icon img src in production - NOT DISPLAYING) I would like to hear your opinion on this problem I am having. I've been struggling with this for quite some time. Perhaps … -
My django app is Not activating after shutting down my PC
when I start a new django Project it works perfectly well but after I shutdown or restart my pc it does not work again. even though I have activated my virtual environment it keeps giving me errors. this what the error says: Traceback (most recent call last): File "C:\Users\SUCCESS-AKINYEMI\Desktop\studybud\manage.py", line 11, in main from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\SUCCESS-AKINYEMI\Desktop\studybud\manage.py", line 22, in main() File "C:\Users\SUCCESS-AKINYEMI\Desktop\studybud\manage.py", line 13, in main raise ImportError( ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? I tried it on another person laptop and it work, but it is not working on my on laptop. -
how to get both ID and names from Many to Many field in Django
i'm creating a messaging app like Whatsapp. i have a Profile model that has Rooms as Many to many relationship. meaning every user will have a list of rooms in which he is added in their profile database. i'm using Rest Framework to fetch the Room info. i'm getting only ID's of the room every time i fetch from the API's. but it would be much easier & optimized for my app if i could also get Names of the Rooms & ID through the profile's Api which has rooms as many to many relation. How can i save both Name & id into a Many to Many field?? #model.py from django.db import models # Create your models here. class Room(models.Model): name = models.CharField(max_length=100,unique=True,blank=True,null=True) def __str__(self): return self.name class Profile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) rooms = models.ManyToManyField(Room) def __str__(self): return self.user.username Serializers.py from django.contrib.auth.models import User from rest_framework import serializers from App.models import * class roomSerializer(serializers.ModelSerializer): class Meta: model = Room fields = '__all__' class userSerializer(serializers.ModelSerializer): class Meta: model = User fields = '__all__' class profileSerializer(serializers.ModelSerializer): class Meta: model = Profile fields = '__all__' views.py from rest_framework.response import Response from rest_framework.decorators import api_view from App.models import * from .serializers import * … -
the field is not shown in the model // Django-rest-framework restfullAPI
I serialized the CustomUser model and I don't output the 'city' key and the 'like' key, and also don't output the 'week_days' key, which contains a list with datetime. How to solve this problem? (it seems like it is possible through extra context and methodfield) My serializers: class CanWorkStaffSerializerLike(serializers.ModelSerializer): class Meta: model = GameTheme fields = '__all__' class CanWorkStaffSerializerCity(serializers.ModelSerializer): class Meta: model = City fields = '__all__' class CanWorkStaffDaysSerializer(serializers.ModelSerializer): class Meta: model = CanWorkDays fields = '__all__' class CanWorkStaffSerializerUser(serializers.ModelSerializer): class Meta: model = CustomUser fields = ['phone', 'email', 'avatar', 'city', 'first_name', 'last_name', 'like', 'is_legionary', 'is_staff', 'is_active', 'date_joined', 'comfortable_time', 'role', 'updated_at', 'future_notification_last_seen_id', 'developing_notification_last_seen_id'] class CanWorkStaffSerializerWeekDays(serializers.Serializer): datetime = serializers.DateTimeField() class CanWorkStaffSerializerFinal(serializers.Serializer): user = CanWorkStaffSerializerUser() week_days = CanWorkStaffSerializerWeekDays(many=True) convenient_day = CanWorkStaffDaysSerializer() My View: class CanWorkStaffAPIView(APIView): def get(self, request, week, token): context = {} try: user = User.objects.get(auth_token__key=token) except User.DoesNotExist: return HttpResponse('некорректная ссылка') todays_date = datetime.date.today() start_week = todays_date - datetime.timedelta(todays_date.weekday()) first_week_day = datetime.datetime.strptime(week + '-1', '%Y-%W-%w') staff_member = StaffMember.objects.get(user=user) if first_week_day.date() < start_week.today(): return HttpResponse('то что было, то прошло...') week_days = [first_week_day + timedelta(x) for x in range(7)] initial = {} for week_day in week_days: if staff_member.can_work.filter(date=week_day): initial[week_day.strftime('%a')] = True if request.method == 'GET': form = CanWorkForm(initial=initial) else: form = CanWorkForm(request.POST) if form.is_valid(): … -
django makemigrations: makemigrations add only id field from model
i'm learning django and python and mongodb. i tried to makemigrations myapp. i get a 0001_initial.py but this file create Id field and not my model fields this is my settings.py content: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'api.apps.ApiConfig' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'myapi.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [BASE_DIR / 'templates'] , 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'myapi.wsgi.application' # Database # https://docs.djangoproject.com/en/4.1/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'djongo', 'NAME': 'apidb', } } my models.py file: from django.db import models # Create your models here. class Student(models.Model): first_name: models.CharField(max_length=100, null=True) last_name: models.CharField(max_length=300, null=True) def __str__(self): return self.first_name + ' ' + self.last_name I'm looking for a solution, but I don't get anything -
Form doesn't appear and work in Django project
I'm relatively new to Django, so I faced one small problem. I read the documentation and decided to make my own comment form that displays at the same page (DetailView), where I display a question detail and all answers related to this question. I tried to make it as documentation says, but it didn't work. I wrote some functions, but they didn't help as well. Then I copied some styles from bootstrap, something appeared, but I still can't post anything. Seems like POST method doesn't work. It was working, when I add the button that leads to the specific page, where users cand leave comments, but I want to show form, display it at the same page, where all answers are displayed. I will appreciate any help, reccomendations and explanations how it works. models.py class Question(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True) title = models.CharField(max_length=250) slug = models.SlugField(max_length=255, db_index=True, verbose_name="URL") detail = models.TextField() date_posted = models.DateTimeField(default=timezone.now) likes = models.ManyToManyField(User, related_name="forum_question") def total_likes(self): return self.likes.count() def __str__(self): return self.title def get_absolute_url(self): return reverse('detail', kwargs={'slug': self.slug}) class Answer(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True) detail = models.TextField() date_posted = models.DateTimeField(default=timezone.now) likes = models.ManyToManyField(User, related_name="forum_answer") def total_likes(self): return self.likes.count() … -
Is there a way to Verify return a form Validation error back to the UI in Django within an Ajax request
I currently have an issue where i am sending formData from the UI through Ajax to the backend, however, i also created an helper function within the form to allow Image compression whilst it receives the data from the frontend. When the form encounters an exception while compressing, it doesn't return the error to the User until the AJAX request has gotten a response from the server and then i reload the page, I am thinking of using JS to reload the page if the response if false to display the error. Is this a better implementation or how should i go about it? -
How can I get data from a user's social network profile in Django
I have a Django project with settings for authorization in social networks, gmail and telegram. Also there are scopes listed for them: Gmail: SOCIAL_AUTH_GOOGLE_OAUTH2_SCOPE = [ "https://www.googleapis.com/auth/userinfo.email", "https://www.googleapis.com/auth/userinfo.profile", ] VK: SOCIAL_AUTH_VK_OAUTH2_SCOPE = ["email"] OK: SOCIAL_AUTH_ODNOKLASSNIKI_OAUTH2_SCOPE = ["GET_EMAIL"] For telegram it hasn't scopes I'm interesting to get data: user.id, mail, etc. after authorization for example to make a link to the social network's page or "mailto:"-link -
manage.py makemigrations ignores models.py
Lately I've been working on a Django 4.1 app, and I've got a model with following fields: from django.db import models from django.utils.translation import gettext_lazy as _ import datetime class CarArticle(models.Model): class manufacturers(models.TextChoices): BMW = 'BMW', _('BMW') AUDI = 'AUDI', _('AUDI') LEXUS = 'LEX', _('LEXUS') MERCEDES = 'BENZ', _('MERCEDES') VOLKSWAGEN = 'VW', _('VOLKSWAGEN') VOLVO = 'VOLVO', _('VOLVO') FORD = 'FORD', _('FORD') SAAB = 'SAAB', _('SAAB') id = models.BigAutoField(primary_key=True) articleId = models.CharField(max_length=10) manufacturer = models.CharField( max_length=5, choices=manufacturers.choices ) series = models.CharField(max_length=255) gen = models.CharField(max_length=255) year = models.CharField(max_length=20) mileage = models.CharField(max_length=20) engSize = models.CharField(max_length=255) fuelType = models.CharField(max_length=255) price = models.CharField(max_length=255) createdAt = models.DateField(auto_created = True,default=datetime.date.today) updatedAt = models.DateField(auto_now=True) Upon changing any field and running py manage.py makemigrations, I'm presented with No changes detected. My admin.py looks like that: from django.contrib import admin from .models import * admin.site.register(CarArticle) Previously, I removed migrations files and folder since I've been remodeling the database over and over. When I migrate with newly set database, I'm presented with these tables only: mysql> show tables; +----------------------------+ | Tables_in_capi_tool | +----------------------------+ | auth_group | | auth_group_permissions | | auth_permission | | auth_user | | auth_user_groups | | auth_user_user_permissions | | django_admin_log | | django_content_type | | django_migrations | | … -
Getting unauthorized(401) while passing token to API call in react redux saga
I am trying to get patient details by in frontend This is my backend function in Django (DRF) @api_view(['GET']) @permission_classes([IsAuthenticated]) def getPatientProfile(request): user = request.user try: patient = Patient.objects.get(user_id=user) print(type(patient)) response = PatientSerializer(patient, many=False) return Response(response.data) except Exception as e: print(e) return Response(e) This is my test call which is working fine in backend GET http://127.0.0.1:8000/profiles/getPatientProfile/ HTTP/1.1 Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNjYwNTgzMjU2LCJpYXQiOjE2NjA1NzYwNTYsImp0aSI6ImY3ZGU2OGEwNTI2ZTRmNzBiZjU2MDExYzgzMjFhODI1IiwiZW1haWwiOiJhbGlzaGJhaHJpYXouc0BnbWFpbC5jb20ifQ.BLjghVEhSjizpuP9BAJHdjGreKMvl5Y1xOmhsQ2lQLM Now this is how I am trying to call API in saga.js but I keep gettig Unauthorized error, I think the issue is in the way I am writing the Authorization: Bearer token line, can anyone help how I can fix this and what the issue is export const getDetailAPIfunction = async token => { try { const response = await axios.get( "http://127.0.0.1:8000/profiles/getPatientProfile/",{ Authorization: 'Bearer ',token, } ); console.log("data recieved = " + response.data); return response.data; } catch (error) { console.log("error = " + error); throw error; } }; function* fetchUserDetail({ payload: token }) { try { const response = yield call(getDetailAPIfunction, token); yield put(getProfileDetailSuccess(response)); } catch (error) { yield put(getProfileDetailFail(error)); } } -
Django - How to copy schema of existing database into test database?
In my django project, I am using an existing database (Postgres) and with python manage.py inspectdb I created models. now I want to write unit tests and my problem is django just creates an empty test database for it, but it doesn't create schemas. I need to django copy the schema of this database into the test database and then I will insert mock data into it. -
Django user login and registration with Github and Google
I want to create a Google and GitHub login and register with Django on the site, Previously I implemented the register and login with email, and I do not use username on this website, and I customized the user model for this. Can someone help me how to do this? -
How do I test django?
I want to unit test my django view and model. I want to test this views.py and model.py. How can I test them on a practical level? Please give me specific code. I would like to code a test that may make errors in more detail, but I am new to django so how do I do it? views.py def view_tv_and_movie_detail(request, type_movie_or_tv, id): """TVかMovieがデータにあったらgetなかったら登録してget""" tv_or_movie_object, _ = TVAndMovie.objects.get_or_create( tmdb_id=id, judge_tv_or_movie=type_movie_or_tv ) detail_tv_or_movie = TvAndMovieDetailhelp(request, tv_or_movie_object, 3) if request.method == "POST": detail_tv_or_movie.post_comment_action() context = detail_tv_or_movie.send_contexts_detail() template_place = "Movie/movie_detail.html" if type_movie_or_tv == "movie" else "Movie/tv_detail.html" return render(request, template_place, context) models.py class TVAndMovie(models.Model): tmdb_id = models.IntegerField( verbose_name="", blank=False, null=False, ) judge_tv_or_movie = models.CharField( blank=False, null=False, default="movie", max_length=20 ) stars = models.FloatField( blank=False, null=False, default=0, validators=[MinValueValidator(0.0), MaxValueValidator(10.0)], ) def get_comments(self) -> object: return Comment.objects.prefetch_related("tv_or_movie").filter( tv_or_movie_id=self.id ) def average_stars(self) -> float: comments = self.get_comments() n_comments = comments.count() if n_comments: self.stars = round( sum([comment.stars for comment in comments]) / n_comments, 3 ) else: self.stars = 0 self.save() return self.stars class Comment(models.Model): comment = models.TextField(max_length=1000) stars = models.FloatField( blank=False, null=False, default=0, validators=[MinValueValidator(0.0), MaxValueValidator(10.0)], ) user = models.ForeignKey(CustomUser, on_delete=models.CASCADE) tv_or_movie = models.ForeignKey(TVAndMovie, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: unique_together = ("user", "tv_or_movie") indexes = [models.Index(fields=["user", … -
Show / Hide a particular field based on custom button click in Django Admin
I have a Django model like this: class Webhook(models.Model): uuid = models.UUIDField(default=uuid.uuid4, editable=False) url = models.CharField(max_length=256) credentials = models.JSONField(null=True, blank=True, default=dict) @admin.register(models.Webhook) class WebhookAdmin(admin.ModelAdmin): list_display = ("id", "uuid", "url") fields = ("uuid", "url", "toggle_credentials_button", "credentials") readonly_fields = ("uuid", "toggle_credentials_button") def toggle_credentials_button(self, obj): return format_html("""<a class="button">Toggle Credentials</a>&nbsp""") toggle_credentials_button.allow_tags = True The Toggle Credentials button shown in the screenshot is a custom button. I want to show/hide credentials field based on the click/toggle of the Toggle Credentials button, i.e. if the credentials field is currently being shown, then hide the field after the button is clicked and vice-versa. By default, the credentials field should always be hidden whenever a user visits the page shown in the screenshot, i.e. the showing of the credentials field shouldn't persist. If the user clicked the Toggle Credentials button to show the credentials field, then goes back to some other pages and again comes to this same page, then he should have to again click the button to view the credentials field. Also please note that I won't be using this in any UI or Frontend, so I need the functionality to work in Django Admin only. How can I achieve this requirement ? Any kind of … -
What is the difference between "return HttpResponseRedirect(reverse("index"))" and "return render(request, "bidder/index.html")"
The instructor prefers the redirect function on that line instead of return render but hasn't clarified why and the differences between the two. -
How to mock a url path returning response in Django / Python?
I have a function like this: def get_some_data(api_url, **kwargs) # some logic on generating headers # some more logic response = requests.get(api_url, headers, params) return response I need to create a fake/mock "api_url", which, when made request to, would generate a valid response. I understand how to mock the response: def mock_response(data): response = requests.Response() response.status_code = 200 response._content = json.dumps(data) return response But i need to make the test call like this: def test_get_some_data(api_url: some_magic_url_path_that_will_return_mock_response): Any ideas on how to create an url path returning a response within the scope of the test (not using urls.py) would be very much appreciated -
How to Add Certificate Validation django_python3_ldap
I'm trying to integrate AD authentication into my application, but my company requires connections over TLS to AD to trust company CA signed certificates to complete the SSL/TLS handshake. How would I go about adding certificate validation to these settings? # LDAP Connection Settings LDAP_AUTH_URL = ['ldap://xxx.xxx.xxx.xx:636', 'ldap://xxx.xxx.xxx.xx:636'] # Initiate TLS on Connection LDAP_AUTH_USE_TLS = True LDAP_AUTH_TLS_VERSION = ssl.PROTOCOL_TLSv1_2 # LDAP Search BASE for Looking up Users LDAP_AUTH_SEARCH_BASE = 'ou=users,ou=authentication,ou=security,dc=corp,dc=companycom,dc=com' # The LDAP class that represents a user. LDAP_AUTH_OBJECT_CLASS = 'user' # User model fields mapped to the LDAP # attributes that represent them. LDAP_AUTH_USER_FIELDS = { 'username': 'SamAccountName', 'first_name': 'givenName', 'last_name': 'sn', 'email': 'EmailAddress', 'manager': 'manager', 'enabled': 'Enabled' } # A tuple of fields used to uniquely identify a user. LDAP_AUTH_USER_LOOKUP_FIELDS = ('username') # Path to a callable that takes a dict of {model_field_name: value}, # returning a dict of clean model data. # Use this to customize how data loaded from LDAP is saved to the User model. LDAP_AUTH_CLEAN_USER_DATA = "django_python3_ldap.utils.clean_user_data" # Path to a callable that takes a user model, a dict of {ldap_field_name: [value]} # a LDAP connection object (to allow further lookups), and saves any additional # user relationships based on the LDAP data. # … -
Default general error message in case of any exception in django
I am developing Restful API using Django. In case of an error instead of raising python default exception or adding try except on every view, is there a way to add a default error message which will be returned? via django settings? via the url's? via a decoretor? thanx in advanced :) Oz -
How to access remote database's tables in Django?
I am accessing the remote database in my Django project as follows: settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', }, 'remote_db' : { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'db_name', 'USER': 'db_user', 'PASSWORD': 'db_password', 'HOST': '192.*.*.*', 'PORT': '1433', } } For accessing default database table's data, I use the following syntax: from app_name.models import mymodel mymodel.objects.all() My remote database has tables like reports, emplayee_data, etc that are already there and my project has no models defined for these tables. I need to access these tables and I am unsure how to perform this action. remote_db.reports.all() -
How can I use parentheses in Django Slug?
How can I use parentheses in Django project slugs? slug = models.SlugField(max_length=100, unique=True, null=True, allow_unicode=True ) -
Using filter to determine if all via foreign key connected Objects to an Object have property
i am trying to get "All People that possess only books they have read". i have models like: class Person(models.Model): id = Integerfield(primary_key=True) class Book(models.Model): id = Integerfield(primary_key=True) owner = ForeignKey("Person") is_read = BooleanField() Now i am trying to filter with Person.objects.filter(book__is_read=True) but i need something like Person.objects.filter(for_all__book__is_read=True) Is there a way to achive this in Django? -
Django model Queryset negation
I am using Django 3.2. I have written a model manager like this: from django.db.models import QuerySet class FooQueryset(QuerySet): def empty_ones(self): return self.filter(some_field__isnull=True) def nonempty_ones(self): return self.exclude(some_field__isnull=True) All though this example is trivial, I want to keep my code DRY, my logic is more complicated and I want to be able to return the negation of the logic defined in a query function. How may I elegantly do so, using Q expressions? -
Unable to display multiple images on the screen with django
I have just started learning the django framework and I am having issues while displaying the images from the database to the frontend of the website. My database is showing the images uploaded but nothing is being displayed on the page itself. This is my models.py class Post(models.Model): title= models.CharField(max_length=255) author= models.ForeignKey(User,on_delete=models.CASCADE) body = models.TextField() def get_absolute_url(self): return reverse('article-detail', args=(str(self.id))) def __str__(self): return self.title + ' | ' + str(self.author) class Images(models.Model): post= models.ForeignKey(Post,on_delete=models.CASCADE ) image= models.ImageField(null=True, blank=True) This is my views.py class ArticleDetailView(DetailView): model = Post template_name= 'article_details.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['imagelist'] = Post.objects.get(id = self.kwargs['pk']) return context def AddPostView(request): model= Images if request.method == "POST": form= PostForm(request.POST) files = request.FILES.getlist("image") if form.is_valid(): f=form.save(commit=False) f.user=request.user f.save() for i in files: img = Images.objects.create(post=f, image= i) img.save() messages.success(request, "New Blog added") return HttpResponseRedirect("/") else: form= PostForm() imageform= ImageForm() return render (request, "add_post.html",{"form":form,"imageform":imageform}) This is my forms.py from django import forms from .models import Images, Post class PostForm(forms.ModelForm): class Meta: model= Post fields = ('title', 'body','author') widgets = { 'title': forms.TextInput(attrs{'class':'form-control'}), 'body': forms.Textarea(attrs={'class':'form-control'}) } class ImageForm(forms.ModelForm): image= forms.ImageField( label="image", widget= forms.ClearableFileInput(attrs={"multiple":True}), ) class Meta: model= Images fields= ("image",) This is my artice-details.html page {% for pimage in imageslist.image_set.all …