Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why does the Django FileInput widget never render a value? Is it a security risk?
In the source code (link) for Django Widgets it's clear that FileInput does not render a value: # django.forms.fields class FileInput(Input): input_type = 'file' needs_multipart_form = True template_name = 'django/forms/widgets/file.html' def format_value(self, value): """File input never renders a value.""" return This is different to other fields such as CharField which returns an initial string: # django.forms.fields def format_value(self, value): """ Return a value as it should appear when rendered in a template. """ if value == '' or value is None: return None if self.is_localized: return formats.localize_input(value) return str(value) Why is this? It means that if you set a default value in a FileField it is not rendered, which can be confusing for the user. Is it a security concern? The value is stil rendered if the user has previously uploaded a file (I assume via the ModelField not the FormField?), so I don't see the difference? -
Django Form.Errors message is not showing and not printing in console
I am learning django forms right now. I can not see the output of the error in the website as a text message, it only shows as a pop-up message with the default error message even though I set my own error message. Also, my console is not printing anything after if form.is_valid(): This is my views.py file: def forms(request): if request.method == 'POST': form = Forms(request.POST) if form.is_valid(): print("hello") form.save() print(form.cleaned_data) return HttpResponseRedirect('/thank_you') else: form = Forms() return render(request, "form/index.html", { 'form': form }) def thank_you(request): return render(request, 'form/thankyou.html') And here's the html file <html lang='en'> <head> <meta charset="UTF-8"> </head> <body> <form action="/thank-you" method="POST"> {% csrf_token %} {{ form.name.label_tag}} <br> {{form.name}} <br> {{form.name.errors}} <button type="submit">Send</button> </form> -
How to update data in html view in Django?
I am building a photo editor in Django. I have attached the main page code that I have so far: https://jsfiddle.net/xfnLc5to/ I want at updating the brightness scale, the effect to be visible on the photo on the left, even before pressing the submit button. How can I achieve this? So far, I managed to get the brightness value after pressing the submit button, in the views script: brightness_value = request.POST.get('brightness') original_photo = request.POST.get('originalPic') The original_photo variable is still None. How to update the brightness on the photo with the selected brightness value from the slider, before pressing the submit button? -
How to Fix error if I run mange.py run server Django version 1.11
if i want to run my manage.py runserver it generate error File "c:\Users\Dell\AppData\Local\Programs\Python\Python39\lib\site-packages\django\contrib\admin\widgets.py", line 151 ('%s=%s') % (k, v) for k, v in params.items(), ^ Syntax Error: Generator expression must be parenthesized -
Can't call .delete() on a user account instance in Django
I am trying to set up a simple view to delete user accounts. However, for whatever reason it returns Field 'id' expected a number but got 'deleted_user'. I don't understand what this means and how to solve this. # View def delete_account(request, username): """ Deletes the user account """ user = Account.objects.get(username=username).delete() return redirect('pollboard') # Model class Account(AbstractBaseUser): email = models.EmailField(verbose_name='email', max_length=60, unique=True) username = models.CharField(max_length=40, unique=True) date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True) email_confirmed = models.BooleanField(default=False) last_login = models.DateTimeField(verbose_name='last login', auto_now=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) profile_image = models.ImageField(max_length=255, upload_to=get_profile_image_filepath, null=True, blank=True, default=get_default_profile_image()) hide_email = models.BooleanField(default=True) # Model Manager class MyAccountManager(BaseUserManager): def create_user(self, email, username, password=None): if not email: raise ValueError("Users must have an email address") if not username: raise ValueError("Users must have a username") user = self.model( email=self.normalize_email(email), username=username, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, username, password): user = self.create_user( email=self.normalize_email(email), username=username, password=password, ) user.is_admin = True user.is_staff = True user.is_superuser = True user.save(using=self._db) return user -
django admin renders links on readonly foreign key to which I don't have permission
I am using the latest django version (3.2.8) and I have the following problem: My user can see model "inspection" via permisson "view_inspection" My user cannot (!) see any foreign keys due to missing permissions The readonly-foreign key is still rendered as a link which leads to a 403 page What I need: Showing just the name of the object and not linking to it. Any ideas how I can fix this? Looks like a bug somehow... Googleing and browsing stack overflow didn't return any solutions. Thx in advance! -
Why I have many numbers after the decimal point with Sum?
I have a problem to recover a sum of float number. I have a Sale object with a total field that is a float. If I do the sum by hand : >>> sales = Sale.objects.all() >>> total = 0 >>> for sale in sales: ... total += sale.total ... >>> print(total) 134479.15 If I use the ORM Sum: >>> Sale.objects.all().aggregate(ca_total=Sum('total'))['ca_total'] 134479.15000000029 -
CSRF verification failed with 403 error when deployed to AWS elastic beanstalk
After creating a Django project in local, where we tested that all the functionality was working as expected, we finally deployed it in Amazon Web Services Beanstalk. But to our dismay, the production app was showing CSRF error which was never seen during the development phase. Here is a sample of the code: models.py class CustomerAccount(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) phone_number = models.CharField(max_length=50,blank=True) first_name = models.CharField(max_length=200, null=True,blank=True) last_name = models.CharField(max_length=200, null=True,blank=True) urls.py urlpatterns = [ path('', views.index, name='customer-index'), ] views.py @login_required(login_url="/login/") def index(request): if request.method == 'POST': form = CustomerForm(request.POST) if form.is_valid(): form.save() return redirect('customers:customer-index') else: form = CustomerForm() context= { 'form': form, } return render(request, 'customers/index.html', context) index.html <div class="col-md-4"> <div class="card p-3 mb-4 mx-2"> <h3 class="text-center">New Customer</h3> <hr> <form method="POST" action="{% url 'customers:customer-index' %}"> {% csrf_token %} {{ form|crispy }} <input class="btn btn-success btn-block" type="submit" value="Add Customer"> </form> </div> </div> Additional details about our configuration: Inside the settings.py, the middleware for CSRF has been added MIDDLEWARE = [ ... 'django.middleware.csrf.CsrfViewMiddleware', ... ] While we did go through some of the solutions that we could find such as adding @csrf_exempt before the views function setting the csrf token age to None added action attribute in the form tag … -
AttributeError when adding an item to a basket
I've been stuck for a while trying to figure why Django throws this AttributeError when attempting to add an item to a basket. The error looks like this: AttributeError: 'Basket' object has no attribute 'save' I've scoured over my code but can't seem to find the issue. I've posted the necessary code below. basket/basket.py: class Basket(): def __init__(self, request): self.session = request.session basket = self.session.get('skey') if 'skey' not in request.session: basket = self.session['skey'] = {} self.basket = basket def add(self, product, qty): """ Adding and updating the users basket session data """ product_id = str(product.id) if product_id in self.basket: self.basket[product_id]['qty'] = qty else: self.basket[product_id] = {'price': str(product.price), 'qty': qty} self.save() def __iter__(self): """ Collect the product_id in the session data to query the database and return products """ product_ids = self.basket.keys() products = Product.products.filter(id__in=product_ids) basket = self.basket.copy() for product in products: basket[str(product.id)]['product'] = product for item in basket.values(): item['price'] = Decimal(item['price']) item['total_price'] = item['price'] * item['qty'] yield item def __len__(self): """ Get the basket data and count the qty of items """ return sum(item['qty'] for item in self.basket.values()) basket/views.py: def basket_summary(request): basket = Basket(request) return render(request, 'main_store/basket/summary.html', {'basket': basket}) def basket_add(request): basket = Basket(request) if request.POST.get('action') == 'post': product_id = … -
Django ManyToMany (m2m) relationship in result table
Hej! I'm having trouble showing the M2M relationships in my rendered result table in Django. I know that I have to follow through the models to get there but something is not working. Does anyone have an idea what I'm doing wrong? # plants/models.py class Plant(models.Model): name = models.CharField( max_length=200 ) plant_type = models.ForeignKey( PlantType, on_delete=models.SET_NULL, blank=True, null=True, related_name="plant_type", ) used_xducts = models.ManyToManyField( Xduct, through="UsedXduct", blank=True, related_name="used_in_plant" ) class PlantType(models.Model): name_english = models.CharField( max_length=200, blank=True ) class UsedXduct(models.Model): class InputOrOutputChoices(models.TextChoices): IN = "in", _("input") OUT = "out", _("output") OWN = "own", _("own technical need") plant = models.ForeignKey( Plant, on_delete=models.PROTECT ) xduct = models.ForeignKey( Xduct, on_delete=models.PROTECT ) def xduct_str(self): return self.xduct def __str__(self): return f"Used xduct of {self.plant} of {self.xduct}" xducts/models.py class Xduct(models.Model): """(temporary) List of all xducts""" code = models.CharField( max_length=20, unique=True ) name_english = models.CharField( max_length=200, unique=True ) def __str__(self): return f"{self.code}" # plants/template.html {% block content %} <div class="row"> <div class="col-md"> <div class="card card-body"> <h5>Plants</h5> </div> <div class="card card-body"> <table class="table table-sm"> <tr> <th>Name</th> <th>Plant type</th> <th>Used Xducts</th> </tr> {% for i in plants %} <tr> <td>{{i.name}}</td> <td>{{i.plant_type}}</td> <td>{{i.used_in_plant.xduct}}</td> </tr> {% endfor %} </table> </div> </div> {% endblock %} 'name' and 'plant_type' are no problem in this example. … -
How to port a Django web app in mobile (iOS & Android)
We have a working WebApp developed with Django, Python and Vue.Js. The application is working ok when it is opened in Mobile devices but we need to do lot of tweaking UI to make it compatible to mobile devices everytime. So we are looking for a way to create a mobile app and also need to update the data irrespective of device that users use. Please let us know whether this can be achievable? Best regards, ~Alam -
Map Flask API and Django app to same database but different tables
I have a database model which is written in Django ORM and the same database is used by Flask using SQLAlchemy for another microservice (where I need only 2/3 new and 1 exiting table) to store and query some data. So when from my Flask API, I run this command- $ flask db migrate $ flask db upgrade I can see that from migrations/versions, it is trying to delete existing tables of my Django app which I don't want to do. So my question is how to run/use Flask SQLAlchemy ORM without touching existing tables of Django app? Also From my Flask app, I want to refer to some of the existing tables of the Django app but am not sure how to do those without creating models on the Flask app because those models are already created by Django APP. N.B For a particular reason I don't want to separate the Flask API to another database -
How to display default value for models.FileField() in template CreateView?
How do I display the default value for models.FileField()? (ref) class MyModel(models.Model): myfile = models.FileField(upload_to='mydocs', default='myfile.txt') FieldField has an undocumented feature that allows a default value to be set using default=. This is a reference to an existing file, usually in the static root. The default form widget for this field is a ClearableFieldInput (ref), which uses django/forms/widgets/clearable_file_input.html as a template: {% if widget.is_initial %}{{ widget.initial_text }}: <a href="{{ widget.value.url }}">{{ widget.value }}</a> {% if not widget.required %} <input type="checkbox" name="{{ widget.checkbox_name }}" id="{{ widget.checkbox_id }}"> <label for="{{ widget.checkbox_id }}">{{ widget.clear_checkbox_label }}</label> {% endif %}<br> {{ widget.input_text }}:{% endif %} <input type="{{ widget.type }}" name="{{ widget.name }}"{% include "django/forms/widgets/attrs.html" %}> However, if default is set (initial being blank), the default value is not shown in the template, which can be confusing to the viewer. They think the field is empty, then on create() the default value is set. I am assuming that the default value is not passed to the template? If so, how can I modify the FileField to pass it? If not, how can I reference it? -
Django - MultiValueDictKeyError request.POST
Im getting MultiValueDictKeyError on my update view, when i add i can add successfully but when i want to update i get this error. I used the same codes by duplicating 4 times, but this time I could not understand why I am having an error. models.py; class problemduyuru(models.Model): olusturulmatarihi = models.TextField(max_length=100, null=True) duyurutipi = models.TextField(max_length=100, null=True) incidentno = models.TextField(max_length=100, null=True) baslangiczamani = models.TextField(max_length=100, null=True) aciklama = models.TextField(max_length=100, null=True) views.py- update def def problemduyurusuupdate(request, id): problemmember = problemduyuru.objects.get(id=id) problemmember.duyurutipi = request.POST['duyurutipi'] problemmember.incidentno = request.POST['incidentno'] problemmember.baslangiczamani = request.POST['baslangiczamani'] problemmember.aciklama = request.POST['aciklama'] problemmember.olusturulmatarihi = request.POST['olusturulmatarihi'] problemmember.save() messages.success(request, 'Alarmlar was updated successfully!') return redirect('/problemduyurusu') html; <form class="form-horizontal" action="problemduyurusuupdate/{{ problemmembers.id }}" method="POST"> {% csrf_token %} <div class="bd-callout bd-callout-danger"> <div class="bd-calloutic bd-callout-dangeric "> <div class="dangericon"></div> <h4 id="asynchronous-methods-and-transitions" style="color: #e70800;"><b>Technology Announcements</b></h4> <h7 id="asynchronous-methods-and-transitions" style="color:red; font-weight: 400; ">Problem Duyurusu</h7></div> <div class="input-group mb-3"> <div class="input-group-prepend"> <span class="input-group-duyuru" id="inputGroup-sizing-default" style="font-weight: 500;">Duyuru Tipi:</span> </div> <input type="text" class="form-control" value="{{ problemmembers.duyurutipi }}" name="dduyurutipi" id="dduyurutipi" aria-label="Default" aria-describedby="inputGroup-sizing-default"> </div> <div class="input-group mb-3"> <div class="input-group-prepend"> <span class="input-group-duyuru" id="inputGroup-sizing-default" style="font-weight: 500;">Incident No:</span> </div> <input type="text" class="form-control" value="{{ problemmembers.incidentno }}" name="dincidentno" id="dincidentno" aria-label="Default" aria-describedby="inputGroup-sizing-default"> </div> <div class="input-group mb-3"> <div class="input-group-prepend"> <span class="input-group-duyuru" id="inputGroup-sizing-default" style="font-weight: 500;">Başlangıç Zamanı:</span> </div> <input type="text" class="form-control" value="{{ problemmembers.baslangiczamani }}" name="dbaslangiczamani" id="dbaslangiczamani" aria-label="Default" aria-describedby="inputGroup-sizing-default"> … -
How to update FileField data only if a new file has been chosen in django or to delete previous one before upload new one
I need your help ... I've got the same question but with another specific class... My needs is to delete previous file before update new one only if field is filled ... If no change regarding file ... 1- When I update with new picture file ... it's ok but it's created a new file with some caracters (moto.jpg > moto_msi2Kup.jpg) ... 2- When I update only with new name (no change on file) ... the image field in database change ... previous it was word/moto.jpg ... after update it changes to moto.jpg (we lost word directory information ... I hope you understood my needs ... in both case I need to unchange image field if FileField is empty ... If FileField is changed .. Delete previous file and upload new one (still with same name) Below views, models and forms.py and a screenshot too ... Thanks for your help ;) views.py def updateWord(request, pk): word = Word.objects.get(id=pk) form = WordForm(instance=word) if request.method == 'POST': form = WordForm(request.POST, request.FILES, instance=word) if form.is_valid(): document = form.save(commit=False) document.name = request.POST['name'] # if not form.data['image'] is None: if request.FILES.get('image'): print("On supprime le fichier") word.delete_file() document.save() message = "Mot ["+request.POST['name'] + "] edité avec … -
form-data not working for ManyToMany field django
I have 2 models - Module and Room. A module can have zero or multiple rooms and a room can be added into multiple modules. So, there is a simple many-to-many relationship between them. In post request, raw-data input works, but not form-data. module/models.py - class Module(models.Model): module_id = models.AutoField(primary_key=True) title = models.CharField(max_length=100) desc = models.TextField() rooms = models.ManyToManyField(Rooms, blank=True) room_list = models.CharField(max_length = 100, blank=True) rooms/models.py - class Rooms(models.Model): room_id = models.AutoField(primary_key=True) title = models.CharField(max_length=100) desc = models.TextField() level = models.CharField(max_length=100) module/serializers.py - class ModuleSerializer(serializers.ModelSerializer): rooms = RoomSerializerWrite(many=True) class Meta: model = Module fields = '__all__' def create(self, validated_data): rooms_data = validated_data.pop('rooms') module = Module.objects.create(**validated_data) for data in rooms_data: room = Rooms.objects.get(**data) module.rooms.add(room) return module def update(self, instance, validated_data): # Updating rooms rooms_data = validated_data.get('rooms') instance.rooms.clear() for room_data in rooms_data: room = Rooms.objects.get(**room_data) instance.rooms.add(room) # Updating other fields fields = [ 'title', 'desc', 'thumbnail', 'is_deleted', ] for field in fields: setattr(instance, field, validated_data[field]) instance.save() return instance rooms/serialier.py - class RoomSerialize(serializers.ModelSerializer): room_id = serializers.IntegerField() class Meta: model = Rooms fields = "__all__" module/views.py - class add_module(APIView): def post(self, request, format=None): # Adding the rooms to module from room_list new_request = request.data.copy() room_list=[] if 'room_list' in new_request: room_list_data = list(new_request['room_list'].split(" ")) … -
django datepicker format change
Im trying to change the datepicker format form mm/dd/yyyy to dd-mm-yyyy. So far I've added DATE_INPUT_FORMATS in settings.py to ['%d-%m-%Y'], but this didnt change anything. I also changing it via jquery based on proposed solution in this site but it didnt help also. <script type="text/javascript"> $(function () { $('#datepicker').datepicker({ dateFormat: 'dd-mm-yy' }); }); </script> Its quite a trivial problem but I cant seem to find a way how to solve it. forms.py class Calendar(forms.DateInput): input_type = 'date' class AdForm(forms.ModelForm): time_limit = forms.DateInput(format=['%d-%m-%Y']) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['time_limit'].widget.attrs.update({'class': 'form-control mb-3 datepicker'}) class Meta: model = Ad fields = ('time_limit') widgets = { 'time_limit': Calendar(), } The result is still as such: -
How to convert python/django string to dictionary? [closed]
I want to convert this "str" to dict ('UK', 'United Kingdom') Convert it to {'UK', 'United Kingdom'} -
Get the user's location with the help of Django and Python
I want to create a site where I can get the exact location of the user with Django and Python.Here 1 and 2 and 3 a few methods are listed, but they use the Google Maps API. I want to use Open Street Map API and I do not want to use Google Map API. Or they use an IP address that apparently does not give the exact location. They also use JavaScript. I want to get the user's location with the help of Django Python. How can I do this? Thanks -
How to add django-crontab in docker container with non-rooted user django project
Working on a Django project which is running on docker-container with python:3.9-alpine3.13 FROM python:3.9-alpine3.13 LABEL maintainer=<do not want to show> ENV PYTHONUNBUFFERED 1 COPY ./requirements.txt /requirements.txt COPY ./app /app COPY ./scripts /scripts WORKDIR /app EXPOSE 8000 RUN python -m venv /py && \ apk add --update --no-cache postgresql-client && \ apk add --update --no-cache --virtual .tmp-deps \ build-base postgresql-dev musl-dev gcc python3-dev bash openssl-dev libffi-dev libsodium-dev linux-headers && \ apk add jpeg-dev zlib-dev libjpeg && \ apk add --update busybox-suid && \ apk --no-cache add dcron libcap && \ /py/bin/pip install --upgrade pip && \ /py/bin/pip install -r /requirements.txt && \ apk del .tmp-deps && \ adduser --disabled-password --no-create-home app &&\ mkdir -p /vol/web/static && \ chown -R app:app /vol && \ chmod -R 755 /vol && \ chmod -R +x /scripts ENV PATH="/scripts:/py/bin:$PATH" USER app CMD ["run.sh"] I used this tutorial for implementation and I don't this error is because of this because I am getting this error. sumit@LAPTOP-RT539Q9C MINGW64 ~/Desktop/RentYug/rentyug-backend-deployment (main) $ docker-compose run --rm app sh -c "python manage.py crontab show" WARNING: Found orphan containers (rentyug-backend-deployment_proxy_1) for this project. If you removed or renamed this service in your compose file, you can run this command with the … -
docker-compose error when deploying portainer
I was deploying django with Portainer. While deploying, the following error occurred in django image log. django.db.migrations.exceptions.InconsistentMigrationHistory: Migration account.0001_initial is applied before its dependency users.0001_initial on database 'default'. I deleted the migrations file and tried to migrate again and deploy, but the same error occurred. maybe I think the problem is probably caused by customizing the User model. What should I do? -
self.action is None in DRF
self.action is None in get_permissions() method. When a url is called that doesn't exist DRF doesn't throw 404 error. that's why somehow action is None in get_permissions() method. Here is the ModelViewSet: class UserViewSet(ModelViewSet): serializer_classes = { "list": UserSerializer, "retrieve": UserSerializer, "create": UserSerializer, "update": UserUpdateSerializer, } http_method_names = ["get", "post", "put"] def get_serializer_class(self): return self.serializer_classes[self.action] def get_permissions(self): if self.action is None: # here error raises when i call '.../accounts/blablabla/` endpoint in post request instead of 404? raise AssertionError("self.action cannot be None") if self.action in ["list", "retrieve"]: return [IsAuthenticated(), IsAdmin()] else: return [AllowAny()] Here is my discussion link #8199 in github. -
Django - return list of dictionaries
I am a beginner, just starting with django. I am working on a function which returns sub_total, tax_amount and grand_total. I have tried it but it is not working as it should. I think the parameters are not correct or maybe something else. Please review this and provide a complete solution if you can. Also I am trying to hit request on Postman. Is it correct: def branch_report(request, params): # branches = BusinessBranch.objects.filter(is_removed=False) # orders = Order.objects.filter(is_removed=False) branches = BusinessBranch.objects.filter(is_removed=False).annotate( sub_total=Sum('orders__sub_total', filter=Q(orders__is_removed=False)), grand_total=Sum('orders__grand_total', filter=Q(orders__is_removed=False)), tax_amount=Sum('orders__tax_amount', filter=Q(orders__is_removed=False)), ).order_by('name') branch_list = [] for branch in branches: branch_obj = {} branch_list_in = list(branch.business_branch.filter(is_removed=False).annotate( sub_total=Sum('business_branch__sub_total', filter=Q(business_branch__is_removed=False)), tax_amount=Sum('business_branch__tax_amount', filter=Q(business_branch__is_removed=False)), grand_total=Sum('business_branch__grand_total', filter=Q(business_branch__is_removed=False)).values('name', 'id', 'sub_total', 'tax_amount', 'grand_total',)).order_by('name') ) branch_obj['sub_total'] = branch.sub_total branch_obj['tax_amount'] = branch.tax_amount branch_obj['grand_total'] = branch.grand_total branch_obj['id'] = branch.id branch_obj['name'] = branch.name branch_obj['branch_list_in'] = branch_list_in branch_list.append(branch_obj) all_total = Order.objects.filter(is_removed=False).aggregate( all_sub_total=Sum('sub_total', filter=Q(is_removed=False)), all_tax_amount=Sum('tax_amount', filter=Q(is_removed=False)), all_grand_total=Sum('grand_total', filter=Q(is_removed=False)), ) all_obj = {} all_obj['all_sub_total'] = all_total['all_sub_total'] all_obj['all_tax_amount'] = all_total['all_tax_amount'] all_obj['all_grand_total'] = all_total['all_grand_total'] return response_format(SUCCESS_CODE, SUCCESSFUL_RESPONSE_MESSAGE, {'branches': branch_list, 'all_total': all_obj}) I want it to return this: { "code": 200, "message": "Request was Successfull", "data": { "branches": [ { "branch_list": [ { "name": "Wahdat", "id": 21, "sub_total": null, "tax_amount": null, "grand_total": null, } ] }, { "branch_list": [ { "name": "WAPDA", "id": … -
line 8: 'empty'. Did you forget to register or load this tag?
I was watching the django tutorial in youtube, and I follow the same step as the professor did. The error came out with the following error: line 8: 'empty'. Did you forget to register or load this tag? <h1>My To do list </h1> <table> <tr> <th>Items</th> </tr>{% for task in tasks % }<tr> <td>{{task.title}}</td> </tr> {% empty %} <h3>No items in list</h3> {% endfor %} </table> -
filer field not returning any image in Django-admin
I am trying to access Django-filer fields in the Admin panel but I am not getting images, i know the storage location set by filer is random, but obj.bg_image_one.image.url doesn't seem to work My Model class CustomFilters(models.Model): input_file = models.ImageField( upload_to='input/images/', blank=True, null=True) name = models.CharField(max_length=50) action = models.CharField(max_length=150, choices=ACTION_CHOICES) is_active = models.BooleanField(default=False) bg_image_one = FilerFileField(null = True,on_delete = models.CASCADE) bg_image_two = FilerFileField(null = True,on_delete = models.CASCADE,related_name="bg_image_two") bg_image_three = FilerFileField(null = True,on_delete = models.CASCADE,related_name="bg_image_three") bg_image_four = FilerFileField(null = True,on_delete = models.CASCADE,related_name="bg_image_four") bg_image_five = FilerFileField(null = True,on_delete = models.CASCADE,related_name="bg_image_five") Admin code class CustomFiltersAdmin(admin.ModelAdmin): list_display = ('name', 'is_active', 'action', 'Input_Image', 'Output_Image','bg_image_one') list_filter = ('name', 'is_active', 'action') search_fields = ('name', 'action', 'created_by') ordering = ('name',) autocomplete_fields = ('user',) readonly_fields = ['Input_Image', 'background_image_1', 'background_image_2', 'background_image_3', 'background_image_4', 'background_image_5', 'Output_Image'] def background_image_1(self, obj): return mark_safe('<img src="{url}" width="{width}" height="auto" />'.format( url=obj.bg_image_one.image.url, width=obj.bg_image_one.image.width, height=obj.bg_image_one.image.height, ) )