Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
NoReverseMatch at / in Django How to pass url
<a class="nav-link active" aria-current="page" href="{% url 'tasks' %}">Tasks</a> When I'm using this template tag I get an error no ReverseMatch. but , <a class="nav-link active" aria-current="page" href="/tasks">Tasks</a> When I'm doing this I get no error. Can someone explain me? urls.py of the project from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('tracker.urls')), path('tasks/', include('tasks.urls')), ] urls.py of the tasks app from django.urls import path from . import views urlpatterns = [ path('', views.tasklist, name="tasklist"), ] views.py of the tasks app from django.shortcuts import render def tasklist(request): return render(request, 'tasks/task_list.html') -
Async function in django that returns a json response
I want to create an async function in django to return a json response but every time a call the function from ajax call i get 500 error cooroutine has no attribute get from asgiref.sync import sync_to_async from django.core.serializers import serialize def _get_data(request): context = {} poi_ids = request.GET.getlist('poi_ids[]') if len(poi_ids)> 0: poi_list = serialize('geojson', Poi.objects.filter(id__in=poi_ids).distinct('name'), geometry_field='geom', fields=('name',)) context['poi_list'] = poi_list return JsonResponse(context) get_poi = sync_to_async(_get_data, thread_sensitive=True) -
Object of type XYZ is not JSON serializable
I'm working on a small project using Django and i'm getting an error : Object of type CustomUser is not JSON serializable This is my code : def sharedContact(self, connectedUser): contactList = [] contacts = ContactCenter.objects.filter(contact_source=connectedUser) | ContactCenter.objects.filter(shared_with=connectedUser) for contact in contacts: users = CustomUser.objects.filter(id=contact.contact_source_id) | CustomUser.objects.filter(id=contact.shared_with_id) for user in users: with schema_context(str(user.username)): tenant = Contact.objects.filter(id=contact.contact) for x in tenant: contactList.append(x) return contactList -
Django cannot save blank value in FloatField
I have a simple model in Django: class Test(models.Model): name = models.FloatField(default=0.0, blank=True) In my views.py, I am fetching user input from a page. The html code is: <form action="{% url 'test' %}" method="POST"> {% csrf_token %} <input type="number" placeholder="Test" class="form-control mb-2" name="test"> <input type="submit" class="btn btn-primary" value="Submit"> </form> The views.py code is: name = request.POST.get('test', '0.0') #I have tried without the '0.0' as well. new_test = Test(name=name) new_test.save() I keep getting the error: ValueError at /test Field 'name' expected a number but got ''. How can I make django save a blank value or '0.0'(default value) or a null value when the user enters nothing. It seems to accept none of these. -
Django form make field readonly depending on Boolean field
I have two fields in models.py: class Post(models.Model): urgency = models.BooleanField(default=False) date_days = models.IntegerField(default=20, validators=[MinValueValidator(5), MaxValueValidator(40)]) def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk':self.pk}) In my views.py I have: class PostCreateView(LoginRequiredMixin, CreateView): model = Post fields = ['urgency', 'date_days'] def clean_field_1(self): if self.instance.urgency: return self.instance.date_days else: return self.cleaned_data.get('date_days') def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) I would like to make field 'date_days' 'readonly' if 'urgency == True', and to enable back again if 'urgency == False'. User can toggle between True/False. -
Django--"Enter a valid date." Error During Update A Model
But when I restart the server using "runserver" command, it works only once, But when I try to edit the model again, it shows the error again. The DateTime field shows no error, same thing happening for all of my model in my project Django Version: Django-3.2.3 Python Version: 3.8 My Error Image of the err My Model from django.db import models from django.urls import reverse from django.contrib.auth.models import User from django.utils.timezone import now from products.models import Products from organizations.models import Persons, Companies ORDER_STATUS_CHOICES = [ ('Processing', 'Processing'), ('Confirmed', 'Confirmed'), ('Delivered', 'Delivered'), ] def increment_order_number(): last_order = Orders.objects.all().order_by('id').last() if not last_order: return 'FEO-0001' order_number = last_order.order_no order_int = int(order_number.split('FEO-')[-1]) new_order_int = order_int + 1 new_order_no = '' if new_order_int < 10: new_order_no = 'FEO-000' + str(new_order_int) if 100 > new_order_int >= 10: new_order_no = 'FEO-00' + str(new_order_int) if 100 <= new_order_int < 1000: new_order_no = 'FEO-0' + str(new_order_int) if new_order_int >= 1000: new_order_no = 'FEO-' + str(new_order_int) return new_order_no # model for order class Orders(models.Model): order_no = models.CharField(max_length=10, unique=True, default=increment_order_number) person_name = models.ForeignKey(Persons, on_delete=models.CASCADE, null=True) company_name = models.ForeignKey(Companies, on_delete=models.CASCADE, null=True) product_name = models.ForeignKey(Products, on_delete=models.CASCADE, null=True) total_weight = models.FloatField(max_length=10) rate_per_kg = models.FloatField(max_length=10) percentage_of_fotka = models.FloatField(max_length=10) percentage_of_moisture = models.FloatField(max_length=10) delivery_deadline = models.DateField(default=now) … -
Django REST: How to return 500 error from custom middleware instead of the KeyError: '...' if a cookie is missing in request?
I have a custom middleware where I check whether incoming requests have a cookie present or not. If the cookie is not present, then it shows KeyError:. [15/May/2021 18:00:05] "GET /api/auth/profile/ HTTP/1.1" 500 62653 Internal Server Error: / Traceback (most recent call last): File "F:\<dir>\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "F:\<dirs\to\middleware>\middleware.py", line 49, in __call__ myCookie = request.COOKIES['my_cookie'] KeyError: 'my_cookie' I want it to return only a 500 Internal Server Error if the cookie is not present. How do I do this? This is my middleware: class AuthMiddleware: def __init__(self, get_response=None): self.get_response = get_response def __call__(self, request): if request.path == '/api/auth/profile/': try: myCookie = request.COOKIES['my_cookie'] // do something with the cookie return self.get_response(request) except jwt.ExpiredSignatureError: // do something return self.get_response(request) Here, I only check whether the token has expired but I couldn't add mechanism to handle a KeyError. How do I do this? -
All my html code of my django project is displayed in orange in pycharm
i'm working on my django project with pycharm and I've a small problem. All my html files are displaying in orange like on the picture. Need help please -
How we can implement debit/credit card implementation in django?
Please guide me on how I can do that. Or If there any tutorials or websites please share them. Thanks. -
history field don't appear in the rst api?
https://django-simple-history.readthedocs.io/en/latest/quick_start.html I am using django simple history and it didn't goes well with me because it is not showing the history table (in form of json of course) and I make a GET request. So, how to use things like singals to record the change and save them by my self? class UsersSerializer(DynamicFieldsModelSerializer): class Meta: model = User fields = '__all__' class User(AbstractUser, PermissionsMixin): username = models.CharField( max_length=30, unique=True, validators=[USERNAME]) email = models.EmailField(max_length=250, unique=True) history = HistoricalRecords() USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['email', ] class UserView(APIView): serializer_class = serializers.UsersSerializer def get(self, request, pk, format=None, ): user = User.objects.get(id=pk) serializer = serializers.UsersSerializer(user) return Response(serializer.data) the api returns this without the hstory field? { "id": 1, "username": "ali", "email": "change@update.com", "first_name": "ali", } -
I cannot supmit the comments for multi posts in Django
I have a feed and in this feed have posts and each post have comments, Now I can submit a comment for just the first post but when I try to come to the second or third post and submit comment this error rais ValueError: The view videos.views.add_comment_post didn't return an HttpResponse object. It returned None instead. I thought that the problem with the posts id conflict with each other so I passed all the comment fields to the template and the same error still happen. "this problem happen with any post except the first one" My comments view comment_form = PostCommentForm(request.POST ) if comment_form.is_valid(): user_comment = comment_form.save(commit=False) user_comment.author = request.user user_comment.save() result = comment_form.cleaned_data.get('content') user = request.user.username return JsonResponse({'result': result, 'user': user}) My Post model class Post(models.Model): author = models.ForeignKey(Account, on_delete=models.CASCADE) article = models.TextField(null=True, blank=True) photo_article = models.ImageField(max_length=255, upload_to=get_poster_filepath) created_date = models.DateTimeField(auto_now_add=True) My comments model class PostCommentIDE(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='ide_com') author = models.ForeignKey(Account, on_delete=models.CASCADE) content = models.TextField() created_date = models.DateTimeField(auto_now_add=True) My comments Form class PostCommentForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) class Meta: model = PostCommentIDF fields = {'post', 'content'} widgets = { 'content': forms.Textarea(attrs={'class': 'rounded-0 form-control', 'rows': '1', 'placeholder': 'Comment', 'required': 'True', }) } def save(self, … -
PLACES API Error with API key integrated in Django
I am trying to use Places API , but the error rate for Places API in concole ois 100%, The error is : This page doesnt load Maps, Javascript console error is Billing is not enabled , but i have enabled the billing and also enabled all the specified APIS , still faceing the same issue I am using the API key in my Django Projects For search results -
Docker-compose, django and pipfile.lock - docker can't install packages from pipfile.lock
After some searches in the internet, I come to ask for your help. I would like to create a server with django in the backend and react in the frontend. Although I do not have any problems with the frontend, I cannot properly initialise the backend with docker-compose. Here is my docker-compose file : version: "3.9" services: # Frontend and backend django_server: container_name: has_server_backend build: ./server depends_on: - mongo_db ports: - "8000:8000" volumes: - ./server:/has_server frontend: container_name: has_server_frontend build: ./frontend command: npm start ports: - "3000:3000" # Services associated mqtt: container_name: mqtt_broker image: eclipse-mosquitto volumes: - ./services/mosquitto/config:/mosquitto/config - ./services/mosquitto/data:/mosquitto/data - ./services/mosquitto/logs:/mosquitto/logs mongo_db: container_name: has_server_mongodb image: mongo restart: always volumes: - ./services/mongo-db/db:/data/db environment: MONGO_INITDB_ROOT_USERNAME: root MONGO_INITDB_ROOT_PASSWORD: mongoadmin MONGO_INITDB_DATABASE: has_server ports: - 27017:27017 mongo-express: image: mongo-express restart: always ports: - 8081:8081 environment: ME_CONFIG_MONGODB_ADMIN_USERNAME: root ME_CONFIG_MONGODB_ADMIN_USERNAME: my_password Here is the docker file for the backend : FROM python:3.8 ENV PYTHONUNBUFFERED 1 COPY . has_server/ WORKDIR /has_server RUN ls -al RUN pip install pipenv RUN pipenv install COPY . ./ EXPOSE 8000 CMD [ "python", "manage.py", "runserver", "0.0.0.0:8000"] Here is my Pipfile.lock: { "_meta": { "hash": { "sha256": "4c26f7511ec3af2303f9a21d47b0a6dc919fcf2a0a32862c85f2e4a23fc694ea" }, "pipfile-spec": 6, "requires": { "python_version": "3.8" }, "sources": [ { "name": "pypi", "url": "https://pypi.python.org/simple", … -
Django make dynamic Q object by list elements
I want to make dynamic q objects by given list. tag_list = ["t1"] # tag list element length is 1 result_list = [] q_objs_list = [] # In this case, I want to make list like below.. # some def needed to do below q_objs = Q() q_objs &= Q(tag="1") result_list.append(q_objs) q_objs_list.append(1) #because positive q_objs is only when tag "1" 1case. q_objs = Q() q_objs &= ~Q(tag="1") result_list.append(q_objs) q_objs_list.append(0) #because positive q_objs is nothing #>>> len(result_list) >>> 2 # In this case, list length is 2 and I want to get 4 results list. tag_list = ["1", "2"] result_list = [] q_objs_list = [] # some def needed to do below q_objs = Q() q_objs &= Q(tag="1") q_objs &= Q(tag="2") result_list.append(q_objs) q_objs_list.append(2) #because positive q_objs is only when tag "1", "2" 2cases. q_objs = Q() q_objs &= Q(tag="1") q_objs &= ~Q(tag="2") result_list.append(q_objs) q_objs_list.append(1) #1 positive case q_objs = Q() q_objs &= ~Q(tag="1") q_objs &= Q(tag="2") result_list.append(q_objs) q_objs_list.append(1) #1 positive case q_objs = Q() q_objs &= ~Q(tag="1") q_objs &= ~Q(tag="2") result_list.append(q_objs) q_objs_list.append(0) # no positive case #>>> len(result_list) >>> 2 * 2 In my case, I don't know what tag_list will be given to me. It could be ["t1", "t2", "t3", … -
Django Rest framework, retrieve data from database with no related model
I am trying to create a REST API for a database that already exists. The problem is that the data on the database are refreshed from a bash script every hour, so there is no related model for these data. So I am working on creating a GET request on Django so to be able to retrieve the data. Currently I am using an APIView like this: class RetrieveData(APIView): def get(self, request): conn = psycopg2.connect(host=..., database=..., user=..., password=..., port=...) cur = conn.cursor() cur.execute(f'Select * from ....') fetched_data = cur.fetchone() cur.close() res_list = [x for x in fetched_data] json_res_data = {"id": res_list[0], "date": res_list[1], "data": res_list[2]} conn.close() The problem that I have is that connecting on the database every time so to retrieve the data and then return the response is quite slow ~ 2sec/request. Also I am afraid in case of many requests made at the same time, how is that going to work. So the question that I have is if there is any suggestions or any solutions that you propose. -
I am getting a 'permission denied' error when I try to upload files directly to my Django app on Elastic beanstalk with a newly attached volume
I recently deployed a django app to AWS elastic beanstalk. I have used boto3 to enable storing my videos to the s3 bucket. But i need to convert the video files on the local storage before storing it on S3. I use moviepy and ffmpeg to convert the videos. But when I try to upload the files, I get an error "[errno 32] broken pipe moviepy error: ffmpeg encountered the following error while writing file /home/ec2-user/mount_point/u3files/temp_files/21editedtemp_mpy_wvf_snd.mp3: /home/ec2-user/mount_point/u3files/temp_files/21editedtemp_mpy_wvf_snd.mp3: permission denied". I have already chmod 777 on the root folder of the volume and 'u3files' folder inside the local storage. Is there anything I am missing? How do I solve this? I am new to AWS beanstalk and any help would be appreciated. Thanks. -
how to prefetch directly unrelated fields in graphene django
I started using graphene and there are some thing I have not yet understood well for instance, when using nodes the I have this query { orders { edges { node { id fromUser { id username userprofile{ image id } } toUser { id username userprofile{ image id } } } } } } it is very nice because it allows me to fetch profile and get image for a given profile that is related to a user even though user is foreign key in profile, however it is expensive in terms of queries that has to be done in order to get profile for every user my models looks like this class Order(models.Model): from_user = models.ForeignKey(User, on_delete=models.PROTECT, related_name="from_user") to_user = models.ForeignKey(User, on_delete=models.PROTECT, related_name="to_user") .... class UserProfile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) image = models.ImageField(null=True) and my query as of now Order.objects.select_related('from_user','to_user').filter( Q(from_user=user) | Q(to_user=user) ).order_by("-id") return orders will appreciate if anyone could help me know how I can prefetch profile for both from_user and to_user in that case coz it really is expensive fetching the profile -
Check file extension in Django FileField
I need to run a different code depending on the extension of the file. This is a simplified version of the model: class SuplierList(models.Model): file = models.FileField(upload_to='fornecedores/') This is the part of the view that I have the problem: table = request.GET.get("table") ft = FornecedorTabela.objects.filter(id=table)[0] file = ft.file if re.match('.pdf$', ft.file.name): I don't know how I should write this last condition above. With this version above, I get the error: The 'python' engine cannot iterate through this file buffer. How show I write this condition? -
Bootstrap only works for the home page of my website, but no other html page. Why?
I am a newbie and trying to create a ecommerce website with Django. I am using Bootstrap 5. Bootstrap is only working on the home page of my website, but not on the other pages... Why is that ? main.html <!DOCTYPE html> {% load static %} <html lang="fr"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link href="static/css/main.css" rel="stylesheet"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.css"> <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script> <style> /*PAYPAL BUTTONS STYLE*/ /* Media query for mobile viewport */ @media screen and (max-width: 400px) { #paypal-button-container { width: 100%; } } /* Media query for desktop viewport */ @media screen and (min-width: 400px) { #paypal-button-container { width: 250px; } } </style> <title> {% block title %} {% endblock title %} </title> </head> <body> <header> <nav class="navbar navbar-expand-lg navbar-light bg-light"> <div class="container-fluid"> <a class="navbar-brand" href="/">MONOÏ</a> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarNav"> <ul class="navbar-nav"> <li class="nav-item"> <a class="nav-link active" aria-current="page" href="/">Home</a> </li> <li class="nav-item"> <a class="nav-link active" aria-current="page" href="/">La marque</a> </li> <li class="nav-item"> <a class="nav-link active" aria-current="page" href="{% url 'store:categories' %}">Catégories</a> </li> <li class="nav-item"> <a class="nav-link active" aria-current="page" href="/all_products/">Tous les produits</a> </li> <li class="nav-item"> <a class="nav-link active" aria-current="page" href="{% url 'contact:contact-form' %}">Contact</a> </li> <li class="nav-item"> … -
How to Implement this custom model manager in django?
am new to Django and I getting some difficulties and I'm confused about the correct way to use Django custom model managers: charities/models.py: from django.db import models from accounts.models import User class Benefactor(models.Model): Level = ((0, 'Beginner'), (1, 'Intermediate'), (2, 'Expert')) user = models.OneToOneField(User, on_delete=models.CASCADE) experience = models.SmallIntegerField(choices=Level, default=0) free_time_per_week = models.PositiveSmallIntegerField(default=0) class Charity(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) name = models.CharField(max_length=50) reg_number = models.CharField(max_length=10) class TaskManager(models.Manager): def related_tasks_to_charity(self, user): my_charity = str(Charity.objects.get(user = user)) return self.filter(charity = my_charity) def related_tasks_to_benefactor(self, user): my_bonefactor = str(Benefactor.objects.get(user = user)) return self.filter(assigned_benefactor = my_bonefactor) def all_related_tasks_to_user(self, user): return self.filter(state = "P") class Task(models.Model): gen_choice = (('F', 'Female'), ('M', 'Male')) sta_choice = (('P', 'Pending'), ('W', 'Waiting'), ('A', 'Assigned'), ('D', 'Done ')) # id = models.AutoField() !REMOVE id FIELDS assigned_benefactor = models.ForeignKey(Benefactor, null=True, on_delete=models.SET_NULL) charity = models.ForeignKey(Charity, on_delete=models.CASCADE, related_name='User_Charity') age_limit_from = models.IntegerField(blank=True, null=True) age_limit_to = models.IntegerField(blank=True, null=True) date = models.DateField(blank=True, null=True) description = models.TextField(blank=True, null=True) gender_limit = models.CharField(max_length=50, blank=True, null=True) state = models.CharField(max_length=50, choices=sta_choice, default='Pending') title = models.CharField(max_length=100) objects = TaskManager() my problem is here and these 3 defines: class TaskManager(models.Manager): def related_tasks_to_charity(self, user): my_charity = str(Charity.objects.get(user = user)) return self.filter(charity = my_charity) def related_tasks_to_benefactor(self, user): my_bonefactor = str(Benefactor.objects.get(user = user)) return self.filter(assigned_benefactor = my_bonefactor) def … -
django model for list aws iam users in admin page
hi iam new for django i am creating a application so that i can list IAM users, policies and also create IAM users I know how to transfer a doc from local machine to s3 bucket but i dont know how to list IAM user in the django application And i have a endpoint for a lambda function so that get the list of IAM user from this i want to create a module so that will list the IAM user Please help me with this... python import uuid from django.db import models from django.contrib.auth.models import User from django.contrib.auth import get_user_model class Docstos3(models.Model): uuid = models.UUIDField( primary_key=True, default=uuid.uuid4, editable=False, ) created_at = models.DateTimeField(auto_now_add=True) title = models.CharField(max_length=100) docs = models.FileField() i want to create a button in admin page so that i can get IAM user when i click that with the help of my Api endpoint -
Django + React Project Works On Local Server But Does Not Display On pythonanywhere.com . . . Do The React Paths Have To Be Defined In Django?
So my django/react project works find on my local machine but when I deploy it to pythonanywhere.com I get this message below when I try to go to any of the routes ("/", "/factors", "/chart"). I have seen some other posts on how to tell django where to go to if the url corresponds to the frontend React routes (since that is the only place the routes are defined) but I'm unsure what to put in the views. Is the only way to get this to work to load a generic html template with a django view and then call the React routes from there? Why does it work in development without doing this but the same url paths don't display anything on the live site? The /api route correctly displays the django api interface so at least I know some routes are working. Page not found (404) Request Method: GET Request URL: https://elledee.pythonanywhere.com/ Using the URLconf defined in factorsViewer.urls, Django tried these URL patterns, in this order: admin/ api/ The empty path didn’t match any of these. Here is my urls.py project file (I don't have a urls.py in the fv app). """time_factor URL Configuration The `urlpatterns` list routes … -
Why i am getting error "page not found" after after making the url dynamic in django
why i am getting this error.. "page not found" while trying to implement dynamic url in django...please see my code and advice me. it works fine when url is not dynamic.but as soon as the url is made dynamic it shows the error view.... def detail_post(request,my_id): return render(request, 'dynamic/showdetail.html') urlpatterns = [ path('detail/<my_id>/', views.detail_post, name="detail") ] it works absolutely fine before dynmic url is made -
list inside dictionary wont appear when sent to a put request
i have a dictionary that should look like this memberlist = [{"id":50,"firstName":"popo"}] data = {"member": memberlist, "len":1} a put request that looks like url = "http://192.168.100.246:8000/api/group/member/28" updategroup = requests.put(url,data = data) and this is the view of the url class SetMember(APIView): permission_classes=[AllowAny] def getObject(self,id): try: return Group.objects.get(id=id) except Group.DoesNotExist: return Response(status = status.HTTP_404_NOT_FOUND) def get(self,request, id): group = self.getObject(id) serializer = setMemberSerializer(group) return Response(serializer.data) def put(self,request,id, format='json'): group = self.getObject(id=id) serializer = setMemberSerializer(group, data=request.data) if serializer.is_valid(): # serializer.save() return Response(serializer.data) return Response ({'msg':request.data}, status = status.HTTP_400_BAD_REQUEST) well the api doesnt work, so i looked around it to see what was wrong by returning request.data as a response. turns out the data returned from the response looked like this {"msg":{"member":"firstName","len":"1"}} while i was expecting the data to look like this {"msg":[{"id":50,"firstName":"popo"}],"len":"1"}} HOWEVER, when i changed the data sent into something like (i added single quotes to the list and didnt use a variable anymore) data = {"member": '[{"id":50,"firstName":"popo"}]', "len":1} everything works fine! any help or tips appreciated would be nice -
upload all the images in a directory to django admin in name and image field respectively?
i am trying to upload a lot of images to the django database through models.py in django admin but am unable to do so. models.py class Category(models.Model): name = models.CharField(max_length=250, unique=True) slug = models.SlugField(max_length=250, unique=True) # description = models.TextField(blank=True) image = models.ImageField(upload_to='category', blank=True) class Meta: ordering = ('name',) verbose_name = 'category' verbose_name_plural = 'categories' def get_url(self): return reverse('products_by_category', args=[self.slug]) def __str__(self): return self.name path1 = "D:/downloads/mobiles/images/" fil = os.listdir(path1) for f in fil: Category.name.save(os.path.basename(os.path.join(path1, f))) Category.image.save(f, File(open(os.path.join(path1, f)), 'r')) this gives error AttributeError: 'DeferredAttribute' object has no attribute 'save' I can't seem understand why is this happening. Also feel free to suggest any other way of doing this.